py magic method

There is a class of methods in Python that start with two underscores and end with two underscores, and are automatically invoked when a certain condition is met. This type of method is called a magic method.

__init__ method

  1. It will be called automatically after the object is created

  1. usage:

  1. Add properties to the object, (initialization method, construction method)

  1. Some code must be executed after each object is created, so this line of code can be written in the __init__ method

  1. Precautions:

  1. don't make a mistake

""""
猫类,属性 name,age,show_info(输出属性信息)
"""

class cat:
    # 定义添加属性的方法
    def __init__(self,name,age):
        self.name = name # 给对象添加 name 属性
        self.age = age # 给对象添加 get 属性

    # 输出属性信息
    def show_info(self):
        print(f'小猫的名字是:{self.name},年龄是:{self.age}')

# 创建对象,不要在自己类的缩进中
b_cat = cat('蓝猫', 2) # 创建对象,会输出
blue = b_cat
blue.show_info()

black_cat = cat('黑猫',3)
black_cat.show_info()

__str__ method

  1. When using print(object) to print an object, it will be called automatically

  1. In this method, the attribute information of the object is generally written, that is, what information you want to view when printing the object is defined in this method. If the __str__ method is not defined in the class, print(object) will output the reference address of the object by default

  1. Note: This method must return a string

class cat:
    # 定义添加属性的方法
    def __init__(self, name, age):
        self.name = name  # 给对象添加 name 属性
        self.age = age  # 给对象添加 get 属性

    def __str__(self):
        return f'小猫的名字是:{self.name}, 年龄是:{self.age}'


# 创建对象,不要在自己类的缩进中
b_cat = cat('蓝猫', 2)
print(b_cat)

black_cat = cat('黑猫', 3)
print(black_cat)

__del__ method (understand)

__init__ method, after the object is created, it will be called automatically (construction method)

__del__ method, when the object is deleted and destroyed, it is automatically called (emmm heritage) (destruction method)

  1. Call the scene, the program code ends, and all objects are destroyed

  1. Call the scene and use del to delete the object directly (if the object has multiple names and multiple objects refer to one object, all objects need to be deleted)

class Demo:
    def __init__(self, name):
        print('我是 __init__,我被调用了')
        self.name = name

    def __del__(self):
        print(f'{self.name} 没了,给它处理')

# Demo('A')
a = Demo('a')
b = Demo('b')
del a
print('代码运行结束')

Guess you like

Origin blog.csdn.net/weixin_56194193/article/details/129124565