将函数委托给类实例属性

时间:2014-05-27 13:30:39

标签: python python-3.x

我想将一些函数从object完全委托给它的属性,而不必在defenition和function的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."""
        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)

我该怎么做?

3 个答案:

答案 0 :(得分:4)

继承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.

答案 1 :(得分:2)

使用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__

输出'Some doc.'

答案 2 :(得分:1)

这是一个简单的解决方案:

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

并且存在属性的实际委派。更多,在空闲状态下,您可以自动完成a.b_func(arg)

相关问题