__new__、__del__

# __new__ 是调用类时第一个调用的方法;
# 默认调用object基类的__new__方法,只在需要控制对象的创建过程时重写;
# 必须返回实例(创建对象)
class T():
    _i = None

    def __new__(cls, **args, **kwargs):
        if cls._i is None:
            cls._i = super().__new__(cls)
        return cls._i

    def __init__(self):
        self.data = []

t1 = T()
t2 = T()
print(t1 is t2) # True 两个实例相同

class F():
    def __new__(cls, value):
        if isinstance(value, int):
            return super().__new__(IntNumber)
        elif isinstance(value, float):
            return super().__new__(FloatNumber)
        raise TypeError("Unsupported type")

class IntNumber():
    def __init__(self, value):
        self.value = value

class FloatNumber():
    def __init__(self, value):
        self.value = value

f1 = F(123)
f2 = F(1.23)
print(f1 is f2) # False 根据数据类型不同,实例化的对象不同

 

 

# __del__ 析构方法(当对象被垃圾回收时调用的方法)
# 主要用作最后的清理机制,但不要依赖它来进行重要的资源清理(删除对象)
# 一般不需要重写
class MyClass():
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f"del {self.name}")

C1 = Myclass('test1')
C2 = Myclass('test2')
del C1
print("****分隔符****")

# 执行结果
"""
del test1
****分隔符****
del test2
"""

# 会发现手动执行和最终对象回收时打印了两次

 

posted @ 2025-02-06 21:13  尐少  阅读(10)  评论(0)    收藏  举报