There are many methods of magic, magic is a kind of common method __init __ (self), class bound object is automatically triggered in python. Then to chat with other magic methods.
__str__ method
This method should return values, and return value is a string type.
# Str method class A: DEF __str__ (self): # print objects self trigger. 1 is the result of cancellation, when the results were not canceled 2 return ' <class A> ' Pass A = A () Print (A) # Results 1: <. __ main __ A object at 0x0000026AF987D208> Results 2: <class A>
__del__ method
This method when the object is deleted at the end of the program (object class disappear) automatically triggers
# Del Method class A: DEF the __del__ (self): # triggered self deleting Print ( ' AAAA ' ) Pass A = A () Print (A)
__call__ method
This function is defined in the class. Object calls this function requires only the object name plus (), you can call this function.
class A: DEF __call__ (Self, args *, ** kwargs): Print ( ' AAA ' ) A = A () A () # perform functions __call__ Results: aaa
__slots__ method
The method of this form is not the form of a function (not DEF), which can be stored to memory partitioning properties suitable size, but also limits the extension of other properties.
# Slots Method Import SYS class A: __slots__ is = [ ' name ' ] # limit attribute class, in this setting, DEF the __init__ (Self, name): the self.name = name A = A ( ' meking ' ) # can not add other property, otherwise an error Print (sys.getsizeof (a)) # memory size class view "" "48
Point of realization of the syntax
In the dot syntax required to achieve getattr, setatter, delattr these functions. getattr, look for a property in the name, no such property will be triggered. setattr, in the name of an attribute assignment is to be triggered. delattr, delete the attribute name will be triggered. getattribute not be used with setatter. Its usage is already a little property value, when you call, it will be triggered.
class A: Age =. 1 # Test getattribute function DEF __getattr__ (Self, Key): return ' getattr ' , Key DEF __setattr__ (Self, Key, value): . Self the __dict__ [Key] = value # attribute value name in the class in the form of key-value pairs dictionary binding Print ( ' setattr ' , Key, value, Self. __dict__ [Key]) DEF __delattr__ (Self, Key): del . Self __dict__ [Key] Print ( ' delattr' , Key) DEF __getattribute__ (Self, Key): # . Attribute exists, the priority attribute name used to perform this function return Key, ' getAttribute ' A = A () Print (a.age) # an attribute does not exist, performing getattr function, and the function returns a value, not written as None a.name = ' value ' # execute when setattr function syntax bind values. No return value del a.name # When you delete a property. Delattr function execution
[] Realization of the syntax
This syntax requires keyword getitem, setitem, setitem, delitem. Call the property names refer to values, you can use the dictionary calls the way.
class A: def __getitem__(self, item): print('getitem') return 'getitem', item def __setitem__(self, key, value): self.__dict__[key] = value print('setitem') return self.__dict__[key], value def __delitem__(self, key): print('delitem') delSelf. the __dict__ [Key] A = A () Print (A [ ' Age ' ]) # class no such attribute name, perform the function getitem A [ ' Age ' ] = 18 is # to perform functions setitem del A [ ' Age ' ] # perform functions delitem
Application of the operator in a subject
Between classes, it may be larger than the size between the objects. The ratio based on the ratio of required rules. In gt, lt, eq can be realized.
class A: DEF the __init__ (Self, name, Age): the self.name = name self.age = Age DEF __gt__ (Self, OTHER): # comparison between the object and the object, IF self.age> other.age: # Comparative standard, by age return True the else : return False a = a ( ' mEKING ' , 20 is ) B = a ( ' meking ' , 18 is ) Print (a> B)
Iterator class definitions
class A: def __init__(self, start, end, step): self.start = start self.end = end self.step = step def __iter__(self, ): return self # 返回本身 def __next__(self): a = self.start self.start += self.step if a < self.end: return a else: raise StopIteration # Terminate the loop. Or will endless loop Print (A (. 1, 10,. 1). The __iter__ ()) # __inter__ method for I in A (. 1, 10,. 1): # iteration values Print (I, End = ' , ' )
Context management class
class A: DEF the __init__ (Self, path): # incoming file path self.file = Open (path) # open file DEF the __enter__ (Self): RES = self.file.read () return RES # returns the object itself DEF the __exit__ (Self, exc_type, exc_val, exc_tb): # exc_type, exc_cal, exc_tb have captured self.file.close () return True with A ( ' a.txt ' ) AS f: Print (f)
Polymorphism
Polymorphism is a concept, the same method can accordingly meet, generating different results can be called polymorphism in python. Calculating strings, lists, dictionaries can be used by the length len () This method, however different results, this may be a phenomenon of polymorphism.
Other methods (also very important)
isinstance (a, b): a substance of the object is determined is not of this type b. Analyzing between objects and classes
issubclass (a, a), determining whether there is inheritance relationship between classes and categories. Analyzing between classes