Learning python (fourteen)-special members of the class

1.__new__() method

__new__() is a static method responsible for creating class instances. It does not need to be decorated with the staticmethod decorator, and this method will be called prior to the __init__() initialization method. Under normal circumstances, the implementation of overriding __new__() will call the super().__new__() of its superclass with appropriate parameters and modify the instance before returning.

Use __new__() when __init__() is not enough.

2.__repr__() method

The attributes can be displayed by overriding the __repr__() method of the class. By default, __repr__() will return "class name+object at+memory address" information related to the caller.

3. __del__() method

Python  constructs the instantiated object of the current class by calling the __init__() method, and the __del__() method to be learned in this section has the opposite function to __init__(), which is used to destroy the instantiated object. In fact, when writing a program, if the previously created class instantiation object is no longer used in the future, it is best to manually destroy it at an appropriate location to release the memory space it takes up (the whole process is called garbage collection (GC)). Whether it is manual destruction or Python automatically destroys it for us, the __del__() method will be called.

Python uses automatic reference counting (ARC for short) to implement the garbage collection mechanism. The core idea of ​​this method is: each Python object will be configured with a counter, the counter value of the initial Python instance object is 0, if a variable refers to the instance object, the value of the counter will increase by 1, and so on; on the contrary, whenever A variable cancels the reference to the instance object, and the counter is decremented by one. If the counter value of a Python object is 0, it means that there is no variable referencing the Python object, which means that the program no longer needs it. At this time, Python will automatically call the __del__() method to recycle it.

4.__dir__() usage

Through this function, all the attribute names and method names owned by an object can be obtained, and the function will return an ordered list containing all attribute names and method names. The internal implementation of the dir() function actually sorts the attribute names and method names returned by the method on the basis of calling the parameter object __dir__() method.

5.__dict__ attribute

Inside the  Python  class, whether it is a class attribute or an instance attribute, it is stored in the form of a dictionary, where the attribute name is used as the key, and the value is used as the value corresponding to the key. In order to make it easier for users to see which attributes are contained in the class, the Python class provides the __dict__ attribute. One thing to note is that this attribute can be called with the class name or the instance object of the class. Directly calling __dict__ with the class name will output the dictionary composed of all the class attributes in the class; while using the instance object of the class to call __dict__ , Will output a dictionary composed of all the instance attributes in the class.

6.setattr() method

The function of the setattr() function is relatively complicated. Its most basic function is to modify the attribute value in the class instance object. Secondly, it can also be implemented to dynamically add properties or methods to the instance object.

The syntax format of the setattr() function is as follows:

setattr(obj, name, value)

7.getattr() function

The getattr() function gets the value of a specified attribute in a certain class instance object. That's right, unlike the hasattr() function, this function will only look up all the attributes contained in the class object.

The syntax format of the getattr() function is as follows:

getattr(obj, name[, default])

Among them, obj represents the specified class instance object, name represents the specified attribute name, and default is an optional parameter used to set the default return value of the function, that is, when the function search fails, if the default parameter is not specified, the program AttributeError will be reported directly, otherwise the function will return the value specified by default.

8.hasattr() function

The hasattr() function is used to determine whether a certain class instance object contains an attribute or method with a specified name. The syntax format of this function is as follows:

hasattr(obj, name)

Where obj refers to an instance object of a certain class, and name represents the specified attribute name or method name. At the same time, the function will feed back the judgment result (True or False) as the return value.

9. issubclass and isinstance functions

Python  provides the following two functions to check the type:

  • issubclass(cls, class_or_tuple): Check whether cls is a subclass of any of the multiple classes contained in the latter class or tuple.
  • isinstance(obj, class_or_tuple): Check whether obj is an object of any of the multiple classes contained in the latter class or tuple.

The usage of issubclass() and isinstance() are similar. The difference is that the first parameter of issubclass() is the class name, while the first parameter of isinstance() is a variable, which also corresponds to the meaning of the two functions: issubclass is used to determine whether it is a subclass, and isinstance() is used to determine whether it is an instance of that class or subclass.

In addition, Python provides a __bases__ attribute for all classes, through which all direct parent classes of the class can be viewed, and this attribute returns a tuple composed of all direct parent classes. Python also provides a __subclasses__() method for all classes, through which you can view all direct subclasses of this class, and this method returns a list of all subclasses of this class.

10__call__() method

  A very special instance method in the Python class is __call__(). The function of this method is similar to overloading the () operator in the class, so that the class instance object can be used in the form of "object name ()" like calling ordinary functions. In Python, any () that can be directly applied to itself and executed is called a callable object. Callable objects include custom functions and Python built-in functions. For callable objects, in fact "name()" can be understood as an abbreviation of "name.__call__()".

The hasattr() function has a flaw in that it cannot determine whether the specified name is a class attribute or a class method. You can use __call__() to make up for the shortcomings of the hasattr() function.

11. Overloaded operators

The so-called overloaded operator refers to defining and implementing a processing method corresponding to the operator in the class, so that when the class object is performing an operator operation, the system will call the corresponding method in the class to process it.

Overloaded operator meaning
__new__ Create the class, create the object before __init__
__init__ The constructor of the class, its function is to do the initialization work when creating the class object.
__of__  Destructor, its function is to reclaim resources when the object is destroyed
__add__ The addition operator +, when the class object X performs operations such as X+Y or X+=Y, this method is called internally. But if the __iadd__ method is overloaded in the class, the class object X will give priority to calling the __iadd__ method when doing X+=Y similar operations.
__radd__ This method will be called when the class object X performs operations similar to Y+X.
__iadd__ Overload the += operator, that is, when the class object X does something like X+=Y, this method will be called.
__or__ "Or" operator |, if there is no overload of __ior__, then in statements like X|Y, X|=Y, the "or" symbol takes effect
__repr__,__str__ Format conversion method, corresponding to the functions repr(X) and str(X) respectively
__call__ Function call, similar to X(*args, **kwargs) statement
__getattr__ Point operation, used to get class attributes
__setattr__ Attribute assignment statement, similar to X.any=value
__delattr__ Delete attribute, similar to del X.any
__getattribute__ Get attributes, similar to X.any
__getitem__ Index operation, similar to X[key], X[i:j]
__setitem__ Index assignment statement, similar to X[key], X[i:j]=sequence
__delitem__  Index and fragment deletion
__get__, __set__, __delete__ Descriptor attribute, similar to X.attr, X.attr=value, del X.attr
__len__  Calculate the length, similar to len(X)
__lt __ , __ gt __ , __ on __ , __ age __ , __ eq __ , __ ne__  Comparisons correspond to the operators of <, >, <=, >=, =, !=, respectively.
__iter__,__next__ In an iterative environment, generate an iterator and remove one, similar to I=iter(X) and next()
__contains__ Membership test, similar to item in X
__index__  Integer value, similar to hex(X), bin(X), oct(X)
__enter__,__exit__ Before performing operations similar to with obj as var on the class object, the __enter__ method will be called first, and the result will be passed to var; before the operation is finally ended, the __exit__ method will be called (usually used to do some cleanup and trimming work )

 

Guess you like

Origin blog.csdn.net/qq_35789421/article/details/113646065