__new__
、__init__
、__call__
、__del__
new
:创建对象实例
cls
),以及实例化时传递的其他参数init
:负责对象的初始化工作
self
),以及实例化传递的其他参数call
:对象被调用时执行的方法
self
)和调用时传递的参数del
:对象被销毁(垃圾回收)时自动调用
new
–>init
–>实例操作(实例调用)–>del
class A:
def __call__(self, *args, **kwargs):
print("run call")
def __new__(cls, *args, **kwargs):
print("run new")
return super().__new__(cls, *args, **kwargs)
def __init__(self):
print("run init")
def __del__(self):
print("run del")
a = A()
a()
print("a do somthing")
a()
# run new
# run init
# run call
# a do somthing
# run call
# run del
__str__
、__repr__
repr
:产生一个字符串,可以通过eval
函数重新得到该对象str
:产生一个字符串,方便阅读__doc__
:不是魔法方法,是一个属性,普通函数也有,返回注释内容class A:
'''
类的注释内容
'''
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"A({self.x}, {self.y})"
def __str__(self):
return f"获取x和y"
def func():
"""
func注释内瓤
:return:
"""
a = A(12,13)
print(repr(a)) # print(a.__repr__())
print(str(a)) # print(a.__str__())
# A(12, 13)
# 获取x和y
print(a.__doc__)
print(func.__doc__)
# 类的注释内容
# func注释内瓤
# :return:
__enter__
、__exit__
with
语句执行管理,确保资源正确获取和释放enter
:进入上下文时操作,如资源、设置环境等
self
with
语句中使用exit
:离开上下文执行的操作,如释放资源、清理环境等
self
, exc_type
, exc_val
, exc_tb
self
:实例对象exc_type
:上下文中代码块发生的异常类型,如果没有就是None
exc_val
:异常值,没有就是None
exc_tb
:异常的追追踪信息对象,没有则为None
True
,压制异常,程序继续运行False
或None
,异常将被传播,程序会中断class Open:
def __enter__(self):
print("enter")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit")
if exc_type is not None:
print(f"exception type:{exc_type}")
print(f"exception value:{exc_val}")
return False
with Open() as my_fp:
print("run my_fp")
# enter
# run my_fp
# exit
__setattr__
、__getattr__
、__delattr__
、__getattribute__
实例.属性
触发getattr
只有属性不存在时才会触发class A:
def __getattr__(self, item):
return f"{item}不存在"
def __setattr__(self, key, value):
# self.key = value # 将会导致循环引用
self.__dict__[key] = value
def __delattr__(self, item):
# del self.item # 将会导致循环引用
del self.__dict__[item]
a = A()
a.name = "bruce"
print(a.name) # bruce
print(a.age) # age不存在
del a.name
.操作
都会执行getattribute
getattr
的时候会再次进入getatter
,不会报错class A:
def __setattr__(self, key, value):
# self.key = value # 将会导致循环引用
self.__dict__[key] = value
def __delattr__(self, item):
# del self.item # 将会导致循环引用
del self.__dict__[item]
def __getattr__(self, item):
return f"{item}不存在"
def __getattribute__(self, item):
print("全部捕获")
return super().__getattribute__(item)
a = A()
a.name = "bruce"
print(a.name)
print(a.age)
del a.name
# 全部捕获
# 全部捕获
# bruce
# 全部捕获
# age不存在
# 全部捕获
__setitem__
、__getitem__
、__delitem__
getitem
:通过索引操作符号[]
获取对象元素时调用setitem
:通过索引操作符号[]
设置对象元素时调用delitem
:通过索引操作符号[]
删除对象元素时调用class MyDict:
def __init__(self):
self.data_dict = dict()
def __getitem__(self, item):
return self.data_dict[item]
def __setitem__(self, key, value):
self.data_dict[key] = value
def __delitem__(self, key):
del self.data_dict[key]
a = MyDict()
a["name"] = "bruce"
print(a['name'])
del a["name"]
print(a["name"]) # 被删除
gt
(greater than)大于
lt
(lower than)小于
eq
(equal)
ne
(not equal)
ge
(greater than or equal)
le
(lower than or equal)
还有其他运算符号等等
class MyMoney:
def __init__(self, money: float):
self.money = money
def __gt__(self, other):
return self.money > other.money
def __lt__(self, other):
return self.money < other.money
def __eq__(self, other):
return self.money == other.money
def __ne__(self, other):
return self.money != other.money
def __ge__(self, other):
return self.money >= other.money
def __le__(self, other):
return self.money <= other.money
money1 = MyMoney(19.9)
money2 = MyMoney(20)
print(money1 < money2) # True
print(money1 == money2) # False
print(money1 <= money2) # True
print(money1 > money2) # False
print(money1 >= money2) # False
print(money1 != money2) # True
__iter__
、__next__
创建可迭代对象
iter
:返回一个可迭代对象
next:迭代返回下一个值
# 斐波那契数列
class Fibonacci:
def __init__(self, end: int):
self.a, self.b = 0, 1
self.end = end
self.start = 0
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b
self.start += 1
if self.start > self.end:
raise StopIteration()
return self.a
for i in Fibonacci(5):
print(i)
# 1
# 1
# 2
# 3
# 5
__get__
、__set__
、__delete__
描述符是哟中通过实现特定协议的类,使得类的属性访问具有可控的行为
描述符主要用于管理属性的访问、修改和删除操作
描述符本质是一个新类,这个类中至少要实现一个,这也被称为描述符协议
class Descriptor:
def __get__(self, instance, owner):
"""
:param instance: 实例对象
:param owner: 拥有者类
:return: 值
"""
print("will get value")
return instance._value
def __set__(self, instance, value):
"""
:param instance: 实例对象
:param value: 值
:return: None
"""
print("will set value")
instance._value = value
def __delete__(self, instance):
"""
:param instance: 实例对象
:return: None
"""
print("will delete value")
del instance._value
class Myclass:
def __init__(self, value):
self._value = value
descriptor = Descriptor()
instance = Myclass("bruce")
instance.descriptor = 100
print(instance.descriptor)
del instance.descriptor
# print(instance.descriptor) # 删除
# will set value
# will get value
# 100
# will delete value