I have a project, with some modules each of which contains a class doing their respective thing. Then I have an API class for the user. The API class instantiate those classes, and should forward/redirect to those who are doing the actual processing. I have the following questions:
How do I do the forwarding without rewriting what seems to me redundant code? For example, say
Foois the API class,Baris a module class, then now I am writing something like:class Foo: def __init__(self, bar: Bar): self.bar = bar def name(self): return self.bar.name()I explicitly wrote
namemethod inFoo, which just returnsname()ofBar. Isn't this redundant? Is there an "automatic" way to forward the call?In the
barclass I'd write some docstrings. Is there a way to "port" these docstrings to the API classFoo? Writing them again inFoowould be redundant and difficult to maintain.
CodePudding user response:
You can assign bar.name to self.name. Same goes for the docstring with the __doc__ attribute of the class:
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
self.name = bar.name
self.__class__.__doc__ = bar.__class__.__doc__
CodePudding user response:
Try redirecting the __getattr__ magic method:
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
def __getattr__(self, attr):
return getattr(self.bar, attr)
This would redirect all functions to the bar variable.
For multiple classes:
class Foo:
def __init__(self, bar: Bar, foo: Foo, blah: Blah):
self.bar = bar
self.foo = foo
self.blah = blah
def __getattr__(self, attr):
if hasattr(self.bar, attr):
return getattr(self.bar, attr)
elif hasattr(self.foo, attr):
return getattr(self.foo, attr)
else:
return getattr(self.blah, attr)
