__SLOTS__: When defining a class, use the __slots__ variable to limit the properties of an instance that can be added
form: __slots__ = [' name ', ' age ']
An instantiated object can only be bound to the name and age property, and other properties cannot be bound
class people: __slots__ = [' name ', ' age '] def __init__ (self,name,age): self.name = name Self.age = AGEP = People (' Laowang ',) print (p.name) p.sex = ' Male ' Print (p.sex)
Execution Result:
Laowangtraceback (most recent): File "c:/", line, in <module> p.sex = ' Male ' attributeerror: ' People ' Object has no attribute ' sex '
You can see that the Name property is initialized successfully and can be accessed, but the sex attribute cannot be added
__call__ method: As long as you define the type, implement the __CALL__ function, this type becomes callable
Class People:def __init__ (self,name): Self.name=name # def __call__ (self, *args, **kwargs): Print ( ' Call ') #p =people (' Egon ') print (callable (people)) print (callable (p)) p ()
The result of the execution is:
True
True
Pager
means that the people and its resulting objects are callable, and that the object () executes the __call__ method
__getitem__, __setitem__, __delitem__ methods: Provides a dictionary for manipulating object properties
class foo: def __init__ (Self,name): self.name=name def __getitem__ (Self, item): # print (' GetItem ', item) return self.__dict__[item] def __setitem__ (Self, key, value): print (' SetItem-----< ') self.__dict__[key]=value def __delitem__ (Self, key): self.__dict__.pop (Key) # self.__ Dict__.pop (Key) # def __delattr__ (Self, item): # print (' Del obj.key when I execute ') # self.__dict__.pop (Item) F=foo (' Egon ') f[' name ']= ' Egon ' Print (f.name) f[' age ']=18print (f.__dict__) del f[' age ']
__iter__, __next__ method: You can implement an iterator protocol that adds two methods to the class definition to make the object instantiated by the class into an iterative object
It is important to note that the __next__ must control the end condition of the iterator, or the cycle will be dead.
The following example uses this principle to realize the function of a simple range () function
Class Range:def __init__ (self,start,stop): Self.start = Start Self.stop = Stop Pass def __iter __: Return self def __next__ (self): if Self.start >= self.stop:raise stopiteration n = Self.start Self.start + = 1 return nfor i in Range (1,10): print (i)
__del__ method: destructor that automatically triggers execution when an object is freed in memory
Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.
Class Open:def __init__ (self,filepath,mode= ' R ', encode= ' Utf-8 '): Self.f=open (Filepath,mode=mode,encoding=encode) def write: Pass def __getattr__ (self, item): Return GetAttr (Self.f,item) def __del__ (self): Print ('----->del ') self.f.close () f=open (' A.txt ', ' W ') F1=fdel fprint (' =========> ')
__enter__, __exit__ method: Implements the context management protocol, the WITH statement, which uses the same statement as the file operation:
With open (' Filepath/filename ', ' R ', encoding= ' utf-8 ') as F: ' code block '
Define the __ENTER__, __exit__ method when the class is defined to let the object produced by the class use the WITH statement
class foo: def __enter__ (self): print (' ===== "Enter ') Return self def __exit__ (SELF,&NBSP;EXC_TYPE,&NBSP;EXC_VAL,&NBSP;EXC_TB): print (' exit ') Print (' Exc_type ', Exc_type) print (' Exc_val ', exc_val) print (' Exc_tb ', EXC_TB) Return truewith foo () as obj: #res =foo (). __enter__ () #obj =res print (' With foo Self code block ', obj) raise nameerror (' name not defined ') print (' ************************************ ') print ('------> ')
The three parameters in __exit__ () represent the exception type, outliers and traceability information, and the code block in the WITH statement has an exception, and the code after the with cannot be executed, but the code outside the With statement block can execute normally if the __exit__ has a return value
__str__ method: When a method of a class is called, this method is called to return a string (for good-looking and printing-related important information)
Meta-class:
A detailed explanation of the meta-class can be found in this article: a deep understanding of the meta-class in Python (Metaclass)
Python advanced programming for object-oriented steps