Python object-oriented There are many special methods, such as __init__ (construction method), __del__ (destructor method), These methods are very important for object-oriented programming, the following is a list of some common special methods
(1) __call__
Class Foo: def __init__ (self): self.name = ' name ' def __call__ (self, *args, **kwargs): print (' call ') return 1r = foo () a=r () #实例后面加括号, executes the __call__ method inside the class, or foo () () to call print (a)
Results
(2) __getitem__, __setitem__, __delitem__
Class Foo: def __init__ (self): self.name = ' name ' def __getitem__ (self, item): print (item) def __ setitem__ (self, key, value): print (key,value) def __delitem__ (self, key): print (key, ' del ') r = Foo () r[' K1fdsfsdfs '] #中括号里面加个值, Called when the default execution of the __getitem__ method r[' Jay '] = #这个的值, will be executed at the time of the call __setitem__ method del r[' xxxx '] #这样会默认调用类里面的__ Delitem__ method
Execution results
If it's a slice or an index, this is the way to do it,
(3) __dict__
View properties or methods within a class or instance
Class B (): Age = All def __init__ (self,name): self.name = name def bobn (self): print (method of ' B ') #super (b,self). __init__ () #A. __init__ (self) #执行父类的构造函数, Send an instance of B to B =b (' Jay ') Print (b.__dict__) # View the methods or properties in the instance print (b.__dict__) #查看类里面的方法或者属性
Results
(4) __doc__ plays the role of annotation
(5) __iter__, which is automatically called when the object is for a bad time
Class B (): ' I am the comment of the class ' Age = __init__ def (self,name): self.name = name # def BOBN (self): # Print (' method of B ') def __iter__ (self): #有yield, is a generator yield 1 yield 2 yield 3obj = B (' Jay ') for I in Obj: #会默认执行类里面的iter方法, that is, an object can be used for loops, because there is a ITER method print (i) inside it
Results
Python object-oriented (5)