class child:
def __init__(self):
self.b = 1
def dosomething(self, a=1):
print("child dosomething", a, self.b)
return 'returning stuff'
class parent:
def __init__(self):
self.child = child()
# I could do this for every func in child:
def dosomething(self, *args, **kwargs):
return self.child.dosomething()
p = parent()
p.dosomething()
Since I don't want to risk typos or forgetting to update the parent this should be done automatically and not like shown above, especially if child has lots of functions.
I was able to do something similar to this by implementing getattr for the parent class, but this way neither my IDE nor the interpreter knows about the methods in parent / child which is not what I want.
Another way I was exploring was to get all methods of the child using
def get_methods(x):
return [
[method, getattr(x, method)]
for method in dir(x)
if callable(getattr(x, method))
if not method.startswith("_")
]
and then somehow attach them to my parent class.
I can do that using setattr(parent,'dosomething',func_from_get_methods(child))
and then call it the same way as before, but this wont work, since parent has no self.b.
So, is there any pythonic way to do this?
P.S. I'm not talking about subclassing.
0 comments:
Post a Comment
Thanks