gpt4 book ai didi

python - 是否可以覆盖类的 __setattr__ ?

转载 作者:太空宇宙 更新时间:2023-11-03 12:48:09 26 4
gpt4 key购买 nike

在 Python 中,我知道可以这样说

>>> class C:
... def __setattr__(self, name, value):
... print("Hey, you can't set {0} to {1}!".format(name, value))
...
>>> x = C()
>>> x.y = 5
Hey, you can't set y to 5!

但以下仍然有效:

>>> C.y = 5
>>> print(C.y)
5

是否有可能获得如下功能:

>>> C.y = 5
Hey, you can't set y to 5!

纯粹出于好奇而提问,因为我真的想不出一个真正实用的例子。

最佳答案

像所有特殊方法一样,__setattr__ is accessed on the type ;对于类的实例,对于类,就是元类

您必须在自定义元类上定义它,而不是直接在类本身上定义它:

class SetAttrMeta(type):
def __setattr__(cls, name, value):
print("Hey, you can't set {0} to {1}!".format(name, value))

class C(metaclass=SetAttrMeta):
pass

Python 然后在 type(C) 的返回值上查找 __setattr__,这里是 SetAttrMeta

演示:

>>> class SetAttrMeta(type):
... def __setattr__(cls, name, value):
... print("Hey, you can't set {0} to {1}!".format(name, value))
...
>>> class C(metaclass=SetAttrMeta):
... pass
...
>>> C.spam = 'eggs'
Hey, you can't set spam to eggs!

关于python - 是否可以覆盖类的 __setattr__ ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com