I have a class with a custom __getattribute__
definition, for example:
class DummyBaseClass:
def __getattribute__(self, name):
#Interesting logging/validation code here
return object.__getattribute__(self, name)
I would like subclasses of this class to also execute what is in the #Interesting code
block when they have their attributes accessed, without explicitly adding a __getattribute__
definition to every subclass.
What is the best way to achieve this?
CodePudding user response:
I think this is what you are looking for:
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)