Main content:
1. Special methods
2. Design mode: Single case mode
1. Special methods
isinstance Determines whether Obj1 is an instantiation of the class B, or the parent class of Class B is instantiated. Yes, return true, not return false
Isinstance (OBJ1,B)
Issubclass Determines whether a class is a derived class of another class.
Print (Issubclass (b,a)) If class B is derived from Class A, then it is ture.
__len__, __hash__ __str__ __repr__
Len (A1) If you perform a Len () operation on an object, he finds the __len__ method in the class from which the object belongs, and must have a return value for the number in this method.
The __hash__ method also has a similar effect.
Example:
class A: def __init__ (self,name,age): = name = Age def__len__(self): return len (self. __dict__= A ('oldboy', +)print(len (A1) )
__str__ method
# print (a) # prints the object, triggering the __str__ method in the class
# str (a) # str (a) will trigger the __str__ method in the class
# print (' printing of such objects:%s '% a) # format output '%s ' a
Repr is a similar approach.
__call__ method
Object () automatically executes the __call__ method in the class
Example:
classA:def __init__(self):Pass deffunc (self):Print(111) def __call__(Self, *args, * *Kwargs):" "various Codes" " #print (666) Print(args)return 'Wusir'A1=A ()Print(A1 ())
__eq__ method
When comparing the two objects instantiated by a class, he automatically triggers the __eq__ in the class.
class A: def __init__ (self): = 1 = 2 def__eq__(self,obj): if and self.b = = obj.b :return== A ()Print (a1 = = B1)
__del__ destructor method
Python garbage collection mechanism
All the variables, classes, and so on that you create in the file. After the execution is complete,
If it is not used for a period of time, he will automatically remove it in memory.
In-depth study: He will mark all your variables, classes, and so on, and will be automatically recycled for a period of time without being called.
class A: def __init__ (self): Pass def __del__ (self): Print (666= A ()
Python Learning Chapter 23rd