You can use a function to determine the type of class isinstance()
.
isinstance()
Determines whether an object is the type itself, or is located on the parent inheritance chain of that type.
>>> a = Animal()
>>> d = Dog()
>>> h = Husky()
>>> isinstance (H, Husky) True
>>> isinstance(h, Dog)True
type()
the basic type of judgment can also be isinstance()
judged by:
You can also determine whether a variable is one of some types, such as the following code to determine whether it is STR or Unicode:
>>> isinstance (' A ', (str, Unicode)) true>>> isinstance (U ' A ', (str, Unicode)) True
Dir ()
Get all the properties and methods of an object
Returns a list that contains a string
If you want to use it len(myObj)
, write a __len__()
method yourself:
>>> class MyObject (object): ... def __len__ (self): ... return 100...>>> obj = MyObject () >>> len (obj) 100
Get object information:
Mates getattr()
, setattr()
and hasattr()
, we can manipulate the state of an object directly:
>>> class MyObject (object): ... def __init__ (self): ... self.x = 9 ... def power (self): ... return self.x * self.x...>>> obj = MyObject ()
>>> hasattr (obj, ' x ') # have attribute ' x '? true>>> obj.x9>>> hasattr (obj, ' y ') # have attribute ' y '? False>>> setattr (obj, ' y ', 19) # Set a property ' Y ' >>> hasattr (obj, ' y ') # have attribute ' y '? True>>> getattr (obj, ' y ') # Gets the property ' y ' 19>>> obj.y # Gets the property ' y ' 19
You can pass in a default parameter and, if the property does not exist, return the defaults:
>>> getattr (obj, ' z ', 404) # Gets the property ' Z ', returns the default value 404404 if it does not exist
You can also get the method of the object:
>>> hasattr (obj, ' power ') # have attribute ' power '? True>>> getattr (obj, ' power ') # Gets the property ' power ' <bound method Myobject.power of <__main__. MyObject object at 0x108ca35d0>>>>> fn = getattr (obj, ' power ') # Gets the property ' power ' and assigns a value to the variable fn>>> fn # fn points to O Bj.power<bound method Myobject.power of <__main__. MyObject object at 0x108ca35d0>>>>> fn () # called FN () is the same as calling Obj.power () 81
Binding:
Http://www.cnblogs.com/yhl664123701/p/6051448.html
#-*-coding:utf-8-*-from Types Import methodtypedef set_age (self, arg): self.age = Argclass Student (object): Passs = Student () #给student Create a method but instead of creating a link here in class, you'll use the external Set_age method with the link to know Student s.set_age = Methodtype (Set_age,s, Student) s.set_age (213) #调用实例方法print s.age
#-*-coding:utf-8-*-from Types Import methodtypedef set_age (self, arg): self.age = Argclass Student (object): Pass# creates a method directly with a class, but at this point, it is still linked in memory outside the class Student.set_age = Methodtype (set_age,student) #此时在创建实例的时候外部方法 set_age These instances are also copied and the Student class points to the same set_age method New1 = Student () new1.set_age (print new1.age)
__slots__
Variable to limit the attributes that the class can add:
It __slots__
is important to note that the __slots__
defined properties work only on the current class and do not work on inherited subclasses:
Unless it is also defined in a subclass __slots__
, the subclass allows the defined property to be its own __slots__
plus the parent class __slots__
.
>>> class Student (object): ... __slots__ = (' name ', ' age ') # defines the name of the property allowed to bind with a tuple ...
Mixin inheritance
In order to better see the inheritance relationship, we have Runnable
Flyable
changed and RunnableMixin
FlyableMixin
Custom Classes
__str__()
Instead __repr__()
, the difference between the two is to __str__()
return the string that the user sees
Class Student (object): def __init__ (self, name): self.name = name def __str__ (self): return ' Student Object (name=%s) '% self.name __repr__ = __str__
__iter__
If a class wants to be used for for ... in
loops, like list or tuple,
You must implement a __iter__()
method that returns an iterative object,
The python for loop then constantly calls the iteration object's method to get the next()
next value of the loop until it exits the loop when it encounters a stopiteration error.
Class Fib (object): def __init__ (self): self.a, self.b = 0, 1 # Initializes two counters A, a def __iter__ (self): return The self # instance itself is an iterative object, so return your def next: self.a, self.b = self.b, SELF.A + self.b # Calculates the next value if SELF.A > 10000 0: # Exit the condition of the loop raise Stopiteration (); Return SELF.A # returns the next value
__getitem__
Although the FIB instance can be used for a for loop, it looks a bit like the list, but using it as a list or not, for example, take the 5th element:
Class Fib (object): def __getitem__ (self, N): A, B = 1, 1 for x in range (n): A, B = B, a + b return A
__getattr__
Normally, when we call a method or property of a class, it will be an error if it does not exist.
Class Student (object): def __init__ (self): self.name = "Michael" def __getattr__ (self, attr): if attr = = ' score ': return 99
>> S.score
99
__call__
You can also define parameters. Making a direct call to an instance is like calling a function, so you can think of the object as a function and the function as an object because there is no fundamental difference between the two.
Through callable()
the function, we can determine whether an object is a callable object.
Class Student (object): def __init__ (self, name): self.name = name def __call__ (self): print (' My name ' is%s. '% self.name)
>>> s = Student (' Michael ') >>> s () My name is Michael.
Dynamically creating classes
>>> def fn (self, name= ' world '): # define function first ... Print (' Hello ',%s. '% name ') ...>>> hello = type (' Hello ', (object,), Dict (HELLO=FN)) # Create Hello class>>> h = Hello () >>> H.hello () Hello, world.>>> print (type (hello)) <type ' type ' >>>> print (type (h)) <class ' __main__. Hello ' >
Error handling
When we think that some code might go wrong, we can try
run this code,
If an error occurs, the subsequent code does not continue to execute,
Instead, jump directly to the error-handling code, which is the except
statement block,
After execution except
, if there is a finally
block of statements, execute the finally
statement block (if any errors will be performed), at this point, the execution is complete
Try: print ' Try ... ' r = 10/0 print ' result: ', rexcept Zerodivisionerror, E: print ' except: ', efinally:< C10/>print ' finally ... ' print ' END '
Python's error is also class, all the error types are inherited from BaseException
, so in the use except
of note that it not only captures the type of error, but also its subclasses "clean sweep"
Try: foo () except StandardError, E: print ' StandardError ' except ValueError, E: print ' ValueError '
The second one except
is never caught ValueError
, because ValueError
StandardError
the subclass, if any, is also captured by the first one except
.
Common error types and inheritance relationships: Https://docs.python.org/2/library/exceptions.html#exception-hierarchy
Log errors
If you do not catch an error, it is natural for the Python interpreter to print out the error stack, but the program is ended. Now that we can catch the error, we can print out the error stack, analyze the cause of the error, and let the program go on.
Python's built-in logging
modules make it very easy to log error messages:
Import loggingdef foo (s): return 10/int (s) def Bar (s): return foo (s) * 2def main (): try: bar (' 0 ') Except StandardError, E: logging.exception (e) main () print ' END '
Through the configuration, the logging
error can also be recorded in the log file, to facilitate the subsequent troubleshooting.
Throw error: Raise
Class Fooerror (StandardError): passdef foo (s): n = Int (s) if n==0: raise Fooerror (' Invalid value:%s ' % s) return 10/n
Re-learning the Python series (ii)? WTF?