特殊方法
1.__init__魔术方法
初始化魔术方法
2.__new__魔术方法
对象初始化:
? 先执行 _ new _ :分配内存空间,并返回构建好的对象(的地址)
? 再执行 _ init _:为构建好的对象赋予初始化
class Pig:
def __new__(cls,*arg,**kwargs):
return object.__new__(cls)
def __init__(self):
print("一只猪诞生了")
p=Pig()
验证__new__魔术方法返回的是self的内存地址
class Pig:
def __new__(cls):
print("分配内存空间.....")
obj=object.__new__(cls)
print(obj)
return obj
def __init__(self):
print(self)
print("一只猪诞生了")
p=Pig()

3.__del__魔术方法
从内存中清除对象,对象会默认执行方法。具体执行的时间节点
class Pig(object):
def __init__(self):
print("对象被初始化了")
def __del___(self):
print("对象被删除了")
p=Pig()
输出:
对象被初始化了
对象被删除了
说明:在实例被创建的时候就自动执行了
class Pig(object):
def __init__(self):
print("对象被初始化了")
def __del___(self):
print("对象被删除了")
p=Pig()
print("程序执行完成了")

del在整个程序被执行完才会被调用
也可以手动的调用
class Pig(object):
def __init__(self):
print("对象被初始化了")
def __del___(self):
print("对象被删除了")
p=Pig()
del p
print("程序执行完成了")

4.__call__魔术方法
对象当作函数执行时会被默认自动调用
class Flight:
def __init__(self,number):
self.number=number
print(f"{number}号航班")
def checkIn(self):
print("办理登机手续")
def securityCheck(self):
print("安全检查")
def boarding(self):
print("起飞,登机")
def __call__(self,*args,**kwargs):
self.checkIn()
self.securityCheck()
self.boarding()
print("__call__被调用了")
f=Flight("CA1426")
f()

5.__str__魔术方法
打印一个对象的时候,默认调用
在使用str()对对象强制类型转换后,输出结果时会调用
class Dog:
def __init__(self,name):
self.name=name
def __str__(self):
return f"这是一条叫{self.name}的狗"
d=Dog("阿毛")
print(d)

class Dog:
def __init__(self,name):
self.name=name
d=Dog("阿毛")
print(d)

注意:返回的一定是一个字符串
class Dog:
def __init__(self,name):
self.name=name
def __str__(self):
return 123
d=Dog("阿毛")
print(d)

通过调用父类对象__str__方法,打印原有的结果
class Dog:
def __init__(self,name):
self.name=name
def __str__(self):
print(super().__str__())
return f"这是一条叫{self.name}的狗"
d=Dog("阿毛")
print(d)
6.__repr魔术方法(对象是可变容器)
repr方法作用和str方法的作用一样,都是输出对象打印的字符串格式。但最大的不同点在于: 在可变容器中,对象打印默认会调用repr方法。
class Dog:
def __init__(self,name):
self.name=name
def __str__(self):
return f"这是一条叫{self.name}的狗"
def __repr__(self):
print("调用repr魔术方法")
return f"dog:{self.name}"
d=Dog("阿毛")
print(d)

直接执行的是str魔术方法,并没有执行repr方法
class Dog:
def __init__(self,name):
self.name=name
def __str__(self):
return f"这是一条叫{self.name}的狗"
def __repr__(self):
print("调用repr魔术方法")
return f"dog:{self.name}"
d=Dog("阿毛")
print(d)
x=[d]
print(x)

|