我有一个元类和和类,都使用__getattribute__
拦截属性调用。他们是这样的:__getattribute__在实例和类
class B(type):
def __getattribute__ (self, name) :
print(f'hello {self}')
return super().__getattribute__(name)
class C(metaclass=B):
MY_ATTR = 'hello attr'
def __getattribute__ (self, name) :
print(f'hello {self}')
return super().__getattribute__(name)
这表现为,我打算:
C.MY_ATTR
# hello <class 'C'>
# 'hello attr'
C().MY_ATTR
# hello <C object at 0x10bcbbda0>
# 'hello attr'
现在我要带从B
和C
重复的代码,并让它继承。幸运我给他们打了电话B
和C
并留下了空间A
。在这里,我们去:
class A:
def __getattribute__ (self, name) :
print(f'hello {self}')
return super().__getattribute__(name)
class B(type, A):
pass
class C(A, metaclass=B):
MY_ATTR = 'hello attr'
不幸的是,这种行为不再像以前那样:
C.MY_ATTR
# 'hello attr'
C().MY_ATTR
# hello <C object at 0x10bcbbda0>
# 'hello attr'
我认为问题是围绕一个元不能够从一个普通类继承的东西,但我不能确定。我也开放给任何其他实现(可能不需要元类)获取相同的行为 - 但我仍然想要调用像C.MISSING
来提高AttributeError
。
也有类似的问题(例如Get attributes for class and instance in python),但它们略有不同,并没有达到我想要的。
感谢
OOC,如果您先从“A”继承,会发生什么情况'B类(A,类型):'? – ShadowRanger
是的,我曾试过这个。 C.MY_ATTR引发异常。 '你好 __getattribute__ TypeError:期待1个参数,得到0' –
freebie