有没有办法让特定 class 的所有子 class 都在访问属性时执行函数?
Is there a way to have all subclasses of a specific class execute a function whenever an attribute is accessed?
我有一个带有自定义 __getattribute__
定义的 class,例如:
class DummyBaseClass:
def __getattribute__(self, name):
#Interesting logging/validation code here
return object.__getattribute__(self, name)
我希望此 class 的子class 也能在访问其属性时执行 #Interesting code
块中的内容,而不显式添加 __getattribute__
对每个子class.
的定义
实现此目标的最佳方法是什么?
我想这就是你要找的:
class DummyBaseClass:
test = 'Hello World'
def __getattribute__(self, name):
#Interesting logging/validation code here
print(f"{self}: __getattribute__ is called")
return object.__getattribute__(self, name)
class DummySubClass(DummyBaseClass):
pass
class AnotherDummySubClass(DummyBaseClass):
def __getattribute__(self, name):
print('Hi, I do more than the others when __getattribute__ gets called')
return super().__getattribute__(name)
class JustAnotherDummySubClass(AnotherDummySubClass):
test_german = 'Hallo Welt'
print(DummyBaseClass().test)
print(DummySubClass().test)
print(AnotherDummySubClass().test)
print(JustAnotherDummySubClass().test_german)
我有一个带有自定义 __getattribute__
定义的 class,例如:
class DummyBaseClass:
def __getattribute__(self, name):
#Interesting logging/validation code here
return object.__getattribute__(self, name)
我希望此 class 的子class 也能在访问其属性时执行 #Interesting code
块中的内容,而不显式添加 __getattribute__
对每个子class.
实现此目标的最佳方法是什么?
我想这就是你要找的:
class DummyBaseClass:
test = 'Hello World'
def __getattribute__(self, name):
#Interesting logging/validation code here
print(f"{self}: __getattribute__ is called")
return object.__getattribute__(self, name)
class DummySubClass(DummyBaseClass):
pass
class AnotherDummySubClass(DummyBaseClass):
def __getattribute__(self, name):
print('Hi, I do more than the others when __getattribute__ gets called')
return super().__getattribute__(name)
class JustAnotherDummySubClass(AnotherDummySubClass):
test_german = 'Hallo Welt'
print(DummyBaseClass().test)
print(DummySubClass().test)
print(AnotherDummySubClass().test)
print(JustAnotherDummySubClass().test_german)