Magic methods in python

Magic methods in python

1,__ del__ method

Destroy magic method
Trigger timing: automatically execute when an object is cleaned up in memory
Parameter: at least one self, receiving object
Return value: None
Function: do some operations during object cleaning
Note: the program calls this method automatically, and we don't need to call it manually.

class Person(object):

    def __init__(self):

    def __del__(self):

person = Person()
person1 = person
print('The program is over')

Output is:

 The program is over

As shown in the above code, when the program runs and there are no more referenced variables__ del__ Will take effect, so it's not when we call this object as we expected__ del__ It takes effect, so it will not be output

2,__ call__ method

call(): the function that is triggered when the object is bracketed
It further blurs the concept between function and object.
Usage: add parentheses after the object to trigger execution. That is, object () or class () ()

class Foo:

    def __init__(self):
    # When you add parentheses to an object, you can customize the function to trigger
    def __call__(self, *args, **kwargs):

obj = Foo()  # Execute__ init__, The Foo memory address is assigned to obj
obj()  # The memory address in parentheses is called

Output is:


As shown in the above code, call__ call__ Foo is not required call. Because when obj=Foo(), the memory address of Foo() has been assigned to obj, obj itself represents the memory address when calling later, and obj() is used as a function

3,__ str__ method

Trigger timing: the function and method that the print object will trigger will be determined by itself
Parameter: a self receive object
Return value: must be of string type
Function: print (object time) to obtain string, which is usually used for shortcut operation

class People:
    school = 'SH'

    # 1. The function and method triggered by the print object will be customized
    # 2. The return value must be of string type
    def __str__(self):

stu = People()

Output is:


stay python When using the print() function to output the object name in, by default, the memory address referenced by the object name will be printed. If you want to print the attribute value of the object, you can use the__ str__(self) this method.

4,__ new__ method

Instantiation magic method
Trigger timing: triggered when the pair is instantiated
Parameter: at least one cls receives the current class
Return value: an object instance must be returned
Working with: instancing objects
Note: the instantiated Object is the underlying implementation of the Object class, and other classes inherit the Object__ new__ To realize the instantiated Object.
Don't touch this magic method. Trigger it first__ new__ Will trigger__ init__

class Person(object):

    # initialization
    def __init__(self):

    # Instantiation method (construction method) -- create object
    def __new__(cls, *args, **kwargs):
        ret = super().__new__(cls) # Calling the parent class__ new__ The () method creates an object and receives the return value with
        return ret # Return object to person

Output is:

<__main__.Person object at 0x0000012173217B80>

As shown in the above code, an object must be created before initialization, so the output is new... Before init

5,getattr,setattr,__ delattr__ function

Getattr: object Property. When the property does not exist, it will be triggered automatically__ getattr__ method

Setattr: when assigning a value to a nonexistent attribute, it will be triggered automatically__ setattr__ method

Delattr: OK when deleting attributes, * * will be triggered automatically__ delattr__ method

    class Foo:
        x = 1

        def __init__(self, y):
            self.y = y

        # When a non-existent property is accessed, it will be triggered automatically
        def __getattr__(self, item):
            print('----> from getattr:The property you are looking for does not exist')

        def __setattr__(self, key, value):
            print('----> from setattr')
            # print(key)
            # print(value)
            # self.key = value  # This is infinite recursion. Think about it
            self.__dict__[key] = value  # It should be used

        def __delattr__(self, item):
            print('----> from delattr')
            # del self.item #Infinite recursion

    obj = Foo(10)
    obj.z = 10
    print(obj.a)  # Nonexistent property

Output is:

----> from setattr
----> from setattr
----> from getattr:The property you are looking for does not exist

Keywords: Python

Added by 22Pixels on Tue, 04 Jan 2022 12:59:45 +0200