python new init魔法方法

 

class Myclass(object):
    def __new__(cls, num): 
        # 至少要有一个参数cls,代表当前类, 此参数(cls)在实例化时
        # 由Python解释器自动识别
        # 第二个参数num虽然不用, 但是必须有
        
        print("__new__method")
        return super(Myclass, cls).__new__(cls)
    
    # __new__先被调用,__init__后被调用,
    # __new__的返回值会传递给__init__方法的第一个参数,
    # 然后__init__给这个实例设置一些参数
    
    def __init__(self, num):
        print("__init__")
        super(Myclass, self).__init__()
        self.num = num
        
    def __del__(self):
        print("__del__")
        

print("===create===")
myclass = Myclass(7)

print("\n===del====")
del myclass

结果:

===create===
__new__method
__init__

===del====
__del__

 

你可能感兴趣的:(python笔记)