zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python:对象的生命周期new-init-call-del

Python对象 生命周期 New call init del
2023-09-14 09:07:15 时间

对象的生命周期:
创建、初始化、使用、垃圾回收

代码示例

# -*- coding: utf-8 -*-

class Demo(object):
    # 创建 反回 类的实例对象
    def __new__(cls, *args, **kwargs):
        print("__new__")
        return super(Demo, cls).__new__(cls, *args, **kwargs)

    # 初始化 只能反回 None
    def __init__(self):
        print("__init__")

    # 使用
    def __call__(self, *args, **kwargs):
        print("__call__")

    # 垃圾回收
    def __del__(self):
        print("__del__")


if __name__ == '__main__':
    demo = Demo()
    demo()
"""
__new__
__init__
__call__
__del__
"""

参考
简述 initnewcall 方法