在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!
Run Code Online (Sandbox Code Playgroud)
但以下仍然有效:
>>> C.y = 5
>>> print(C.y)
5
Run Code Online (Sandbox Code Playgroud)
是否有可能获得以下功能:
>>> C.y = 5
Hey, you can't set y to 5!
Run Code Online (Sandbox Code Playgroud)
完全出于好奇,因为我无法想到一个真正实用的例子.
像所有特殊方法一样,__setattr__访问类型 ; 对于类的实例,对于类,即元类.
您必须在自定义元类上定义它,而不是直接在类本身上定义它:
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
Run Code Online (Sandbox Code Playgroud)
Python然后查找__setattr__返回值type(C),这是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!
Run Code Online (Sandbox Code Playgroud)