Introduction to python-common magic methods

First of all, what is the magic method?
One, the magic method
1 Overview

(1) If the method name in python is xxx (), then it has a special function, so it is called a "magic" method

(2) In fact, every magic method is rewriting the built-in methods (str, del, etc.))

1. __init__() method

The initialization method that is called when an instance is created is called by default when the object is created.
The __init__() method has a parameter named self by default. If two parameters are passed when creating the object, the __init__() method needs two parameters in addition to “self” as the first parameter. Formal parameters, such as __init__(self,x,y).
Previously, we added attributes to objects like this:

class student:
    pass
    
stu1 = student()

stu1.name = "tan"
stu1.age = 18

Now we use the __init__() method to simplify the code

class student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
stu1 = Student("tan", 20)

This way the code will look more concise, and later calls only need to be given 2 parameters.

2. The str () method

Generally used to describe the object, or define a result you want to output.
When calling str(), __str__() is called, that is, the object is coerced into a string type.
When using print() to output the object, the __str__() method will also be called. As long as you define the __str__() method yourself, the data in the return in this method will be printed.
When the __str__() method is not defined:

class student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
stu1 = student("tan", 20)
print(stu1)

s = str(stu1)
print(s)

"""

Output result:
< main .student object at 0x012B23DC>
< main .student object at 0x012B23DC>
"""

When the __str__() method is not defined, it returns the memory address of the object by default.

If the __str__() method is defined like this:

class student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return "name:%s \t age:%d"%(self.name, self.age)
    
stu1 = student("tan", 20)
print(stu1)

s = str(stu1)
print(s)

"""
输出结果:
姓名:tan  年龄:20
姓名:tan  年龄:20
"""

3. The call () method

Set a call() in the class, and you can directly make the instance of this class be called like a function in the main program: x(a, b) calls x. call (a, b)

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author
    def __str__(self):
        return '<Book: %s>' % self.title
    def __call__(self):
        print('《%s》 is written by %s.' % (self.title, self.author))
if __name__ == '__main__':
    pybook = Book('Core Python', 'Weysley')
    print(pybook)  # 调用__str__
    pybook()   # 调用__call__

4. The del () method

When deleting an object, the python interpreter will call a method by default, which is the __del__() method.
First of all, we should understand a concept, that is, the number of object references. We need getrefcount() in the sys module to measure the number of references to an object, and the return value = actual number of references + 1. If it returns 2, it means that the actual number of references of the object is 1, and at this time, 1 variable refers to the object.

import sys
class A:
    pass
a = A()
###### 现在只有变量a引用了A类创建的对象
print(sys.getrefcount(a))
"""

Output result:
2
"""

Then now create a variable b, and also refer to the object referenced by a, then its number of references will increase by 1, and the actual number of references will become 2.
b = a
print(sys.getrefcount(a))
"""

Output result:
3
"""

When the python interpreter detects that the actual number of references to this object is 0, it will delete this object, and the __del__() method will be called accordingly. Another situation is that the program has been executed completely, then the corresponding memory will be released, and it will also execute the __del__() method.
This is the situation when the program is executed normally:

import sys
class A:
    def __del__(self):
        print("该对象被销毁")
a = A()
"""

Output result:
the object is destroyed
"""

There is also a case of manually deleting variable references:

import sys
class A:
    def __del__(self):
        print("该对象被销毁")
a = A() # 此时实际引用个数为1
b = a # 此时实际引用个数为2

print("删除了变量a") 
del a # 删除变量a,此时实际引用个数为1

print("删除了变量b") 
del b # 删除变量b,此时实际引用个数为0,python解释器就会删除该对象,即调用__del __()方法
print("程序结束")
"""

Output result:
the variable a is
deleted, the variable b is deleted,
the object is destroyed, the
program ends
"""

5. New () method

•__New__ is also a method called when the class creates an instance, it is called earlier than __init__.
•__New __ must have at least one parameter cls, which represents the class to be instantiated. This parameter is automatically provided by the python interpreter during instantiation.
•__New__ must have a return value to return the instantiated instance. Pay special attention to this when you implement __new__ yourself. You can return the instance from the parent class __new__, or directly from the object's __new__. Instance. In Python3, every class inherits the object parent class by default.
• __init__ has a parameter self, which is the instance returned by this __new__. __init__ can complete some other initialization actions on the basis of __new__, and __init__ does not require a return value

class A:
    def __init__(self):
        print("调用了init方法")

    def __new__(cls):
        print("调用了new方法")
        return super().__new__(cls)
a = A()

"""

Output result:
called the new method,
called the init method
"""

Extension: You can implement a singleton mode code by rewriting the __new__ method as follows:
class A:
    # 定义一个私有的类属性,用于存储实例化出来的对象
    _isinstance = None
    
    def __new__(cls):
        print("调用了new方法")
        # 判断如果_isinstance为None,则创建一个实例,否则直接返回_isinstance
        if not cls._isinstance:
            cls._isinstance = super().__new__(cls)
        return cls._isinstance


print(id(A))
print(id(A))
print(id(A))
print(id(A))
"""

Output result:
154624
154624
154624
154624
"""

6. Slots() method

__slots __attributes We all know that python is a dynamic language, and attributes can be added during the running of the program. What if we want to limit the properties of the instance? For example, only the name and age attributes are allowed to be added to the Person instance. In order to achieve the limit, Python allows defining a special __slots__ variable when defining a class to limit the attributes that can be added to the class instance:

class Result(object):
    __slots__ = ("name", "age") 
R = Person() 
R.name = "tan" 
R.age = 20 
R.score = 100

"""

输出结果:
Traceback (most recent call last):
File “”, line 6, in
AttributeError: ‘Person’ object has no attribute ‘score’
“”"

Note: When using __slots__, please note that the attributes defined by __slots__ only apply to the current class instance, and have no effect on inherited subclasses.

Supplement: Introduction to Magic Methods

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45942735/article/details/104539400