python中的魔法方法
__init__:类实例化会触发
class Student(): def __init__(self): print('类实例化会触发__init__方法') Student() # 类实例化会触发__init__方法
__str__:打印对象会触发
class Student: def __init__(self,name,age): self.name = name self.age = age # def __str__(self): # return '%s的年龄是:%d' % (self.name,self.age) yuan = Student('yuan',20) print(yuan) # 不定义__str__的结果:<__main__.Student object at 0x000002045FC47C40> # 定义__str__的结果:yuan的年龄是:20 # 调用时机 使用print打印对象(类的实例化得到的对象)的时候会使用到__str__方法 1.如果没有定义__str__方法,print(对象)则会打印对象的引用地址 2.如果自己定义了__str__方法,print(对象)则会打印方法的返回值 # 注意事项 必须使用return且返回字符串类型
__call__:对象()触发,类也是对象 类(),类的实例化过程调用元类的__call__
# 作用:将实力换对象变成一个可调用对象(判断一个对象是否是可调用对象:通过内置函数callable判断) print(callable(对象)) # True class People(object): def __init__(self,name): self.name=name def __call__(self,friend): print(self.name) a = People('yuan') a.__call__('yue') # 调用方法一 a('yue') # 调用方法二 a('yue')等价与a.__call__('yue') # 当没有定义__call__时,TypeError: 'People' object is not callable # 当定义了__call__时,则执行__call__方法
__new__:在类实例化会触发,它比__init__早
实例1:先调用__new__()方法再调用__init__()方法
class Person(object): def __new__(cls): print("__new__ called") return super().__new__(cls) def __init__(self): print("__init__ called") a = Person() # 结果: __new__ called __init__ called
实例2:__new__()方法构造一个类实例,并将该实例传递给自身的__init__()方法,即__init__()方法的self参数
class Person(object): def __new__(cls): print("__new__ called") instance = super().__new__(cls) print(type(instance)) print(instance) print(id(instance)) return instance def __init__(self): print("__init__ called") print(id(self)) b = Person() # 结果: __new__ called <class '__main__.Person'> <__main__.Person object at 0x1093c1580> 4449899904 __init__ called 4449899904
实例3:如果__new__()方法不返回任何实例的话,init()方法将不会被调用
class Person(object): def __new__(cls): print("__new__ called") def __init__(self): print("__init__ called") c = Person() # 结果: __new__ called
实例4:如果__new__()方法返回一个其他类的实例的话,那它自身的__init__()方法将不会被调用。而且,new()方法将会初始化一个其他类的对象
class Animal(object): def __init__(self): print("animal __init__") class Person(object): def __new__(cls): print("__new__ called") return Animal() def __init__(self): print("__init__ called") d = Person() print(type(d)) print(d) # 结果: __new__ called animal __init__ <class '__main__.Animal'> <__main__.Animal object at 0x000002CEF4DBF010>
实例5:如果重写__new__()方法时,除了cls参数外不再设置其他参数的话,将无法用__init__()方法来设置初始化参数
class Person(object): def __new__(cls): print("__new__ called") instance = super().__new__(cls) return instance def __init__(self, name): print("__init__ called") self.name = name e = Person("Eric") print(e.name) # 结果: Traceback (most recent call last): File "example.py", line 102, in <module> e = Person("Eric") TypeError: __new__() takes 1 positional argument but 2 were given
实例6:在重写__new__()方法时,需要在参数中加入*args,**kwargs,或者显式地加入对应的参数,才能通过__init__()方法初始化参数
class Person(object): def __new__(cls, *args,**kwargs): # Or def __new__(cls, name) print("__new__ called") instance = super().__new__(cls) return instance def __init__(self, name): print("__init__ called") self.name = name e = Person("Eric") print(e.name) # 结果: __new__ called __init__ called Eric
__del__:del 对象和对象回收的时候触发
class Animal(object): def __init__(self): print("animal __init__") class Person: def __del__(self): print("销毁对象:{0}".format(self)) p1 = Person() # 5.销毁对象:<__main__.Person object at 0x000001DFCD279FC8> print(id(p1)) # 1. 2060731260872 p2 = Person() # 3. 销毁对象:<__main__.Person object at 0x000001DFCD284088> print(id(p2)) # 2. 2060731302024 del p2 print("over") # 4. over # 2063785424400 # 2063785422432 # 销毁对象:<__main__.Person object at 0x000001E083326E60> # over # 销毁对象:<__main__.Person object at 0x000001E083327610>
__setattr__,__getattr__:(.拦截方法),当对象.属性-->赋值会调用__setattr__方法,如果取值会调用__getattr__方法
                    
                
                
            
        
浙公网安备 33010602011771号