Suppose I have a couple of classes:
class MyBaseClass:
def method1(self):
print('Hello 1')
class MyClass2:
def __init__(self, inp):
self.old_class = inp
def __getattr__(self, item):
if hasattr(self, item):
print('Hello!')
return getattr(self,item)
else:
return getattr(self.old_class, item)
def method2(self):
print('Hello 2')
What I want to do is print "Hello" when the method called is defined directly as part of that class. For example:
MyBaseClass().method1()
'Hello 1'
MyClass2(MyBaseClass()).method1()
'Hello 1'
MyClass2(MyBaseClass()).method2()
'Hello!'
'Hello 2'
I am also aware that my issue is that __getattr__ isn't called unless __getattribute__ fails. My question is either:
- How can I define
__getattribute__to achieve this without running into recursion errors.
or 2) Is there something I can use instead of __getattribute__ to achieve this.
I don't want to add print('Hello!') to the method defined in MyClass2 (e.g. I would like something that generalises to multiple methods without putting print('Hello!') inside each of them.
Sounds like your code design/architecture is not so smart as it may be.
Usually inheritance and mixins are using to extend classes:
If you want to assign new methods to new classes dynamically you may use
type:But let's suppose that you are completelly understanding what you want to implement and design of code in your question is one possible correct way.
In this case you have to implement
__getattribute__like: