在 python class 中 forward/redirect methods/attributes 没有多余 code/docstrings 的最佳方法?
Best way to forward/redirect methods/attributes in python class without redundant code/docstrings?
我有一个项目,其中有一些模块,每个模块都包含一个 class 做各自的事情。然后我有一个 API class 给用户。 API class 实例化那些 classes,并且应该 forward/redirect 给那些正在做实际处理的人。我有以下问题:
如何在不重写在我看来是冗余代码的情况下进行转发?例如,说 Foo
是 API class,Bar
是一个模块 class,那么现在我写的是:
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
def name(self):
return self.bar.name()
我在 Foo
中明确写了 name
方法,它只是 Bar
的 returns name()
。这不是多余的吗?是否有一种“自动”方式来转接电话?
在 bar
class 我会写一些文档字符串。有没有办法将这些文档字符串“移植”到 API class Foo
?在 Foo
中再次编写它们将是多余的并且难以维护。
您可以将 bar.name
分配给 self.name
。具有 class:
的 __doc__
属性的文档字符串也是如此
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
self.name = bar.name
self.__class__.__doc__ = bar.__class__.__doc__
尝试重定向 __getattr__
魔术方法:
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
def __getattr__(self, attr):
return getattr(self.bar, attr)
这会将所有函数重定向到 bar
变量。
对于多个 类:
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)
我有一个项目,其中有一些模块,每个模块都包含一个 class 做各自的事情。然后我有一个 API class 给用户。 API class 实例化那些 classes,并且应该 forward/redirect 给那些正在做实际处理的人。我有以下问题:
如何在不重写在我看来是冗余代码的情况下进行转发?例如,说
Foo
是 API class,Bar
是一个模块 class,那么现在我写的是:class Foo: def __init__(self, bar: Bar): self.bar = bar def name(self): return self.bar.name()
我在
Foo
中明确写了name
方法,它只是Bar
的 returnsname()
。这不是多余的吗?是否有一种“自动”方式来转接电话?在
bar
class 我会写一些文档字符串。有没有办法将这些文档字符串“移植”到 API classFoo
?在Foo
中再次编写它们将是多余的并且难以维护。
您可以将 bar.name
分配给 self.name
。具有 class:
__doc__
属性的文档字符串也是如此
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
self.name = bar.name
self.__class__.__doc__ = bar.__class__.__doc__
尝试重定向 __getattr__
魔术方法:
class Foo:
def __init__(self, bar: Bar):
self.bar = bar
def __getattr__(self, attr):
return getattr(self.bar, attr)
这会将所有函数重定向到 bar
变量。
对于多个 类:
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)