Python 将函数委托给类实例属性
我想将一些函数从对象完全委托给它的属性,而不必重复defention和函数的docstring中的参数Python 将函数委托给类实例属性,python,python-3.x,Python,Python 3.x,我想将一些函数从对象完全委托给它的属性,而不必重复defention和函数的docstring中的参数 class A: def __init__(self): self.b = B() # I want to replace func below with something more beautiful. def b_func(self, arg): """Here I copied doc from class B."""
class A:
def __init__(self):
self.b = B()
# I want to replace func below with something more beautiful.
def b_func(self, arg):
"""Here I copied doc from class B."""
return self.b.b_func(arg)
class B:
def b_func(self, arg):
"""Some doc."""
print('ok', arg)
# I use b_func directly from A class
a = A()
a.b_func('test')
# May be we can also get b_func with it's doc here?
help(A)
如何执行此操作?使用
getattr
方法返回对由指定的类实例属性的引用
名称如下:
class A:
def __init__(self):
self.b_func = getattr(B(), 'b_func')
class B:
def b_func(self, arg):
"""Some doc."""
print('ok', arg)
# I use b_func directly from A class
a = A()
a.b_func('test')
print a.b_func.__doc__
输出“一些文档”。继承
B
可以解决问题
import types
class B:
def b_func(self, arg):
"""Some doc."""
print('ok', arg)
class A(B):
def __init__(self):
pass
a = A()
a.b_func('test')
help(A)
输出是
('ok', 'test')
Help on class A in module __main__:
class A(B)
| Methods defined here:
|
| __init__(self)
|
| ----------------------------------------------------------------------
| Methods inherited from B:
|
| b_func(self, arg)
| Some doc.
以下是一个简单的解决方案:
class B:
def b_func(self, arg):
"""Some doc."""
print('ok', arg)
class A:
def __init__(self):
self.b = B()
self.b_func = b.b_func
b_func = B.b_func
您可以获得以下要求:
a.b_func('test') => ok test
help(A) => correct reference for b_func
并且存在对属性的实际委托。更重要的是,在idle中,你可以自动完成
a.b_func(arg)
只需澄清一下,你在问如何调用b_func()
类b
的b_func()
?Tim Castelijns,我想替换类a中b_func的定义(删除a.b_func和b_func中的重复参数),但我也需要帮助(a)将b_func显示为类A成员(就像问题代码中发生的那样)。您不需要getattr
来执行此操作self.b_func=b().b_func
工作正常。此外,我不确定这是否是询问者正在寻找的解决方案,因为help(A)
(和pydoc
等)不会选择A.b_func
,即使你知道文档字符串在那里,仍然可以手动访问它,如你所示。吹毛求疵:你是从b
继承的,而不是覆盖它。