Python - 方法链接来自不同类的实例

时间:2014-10-23 15:31:08

标签: python method-chaining

我知道如何在单个类中实现Python中的方法链接,但我想知道是否有办法从不同的类链接方法,如:

class C1:

    def sayHello(self):

        print "hello from c1"

        return self

class C2:

    def sayHello(self):

        print "hello from c2"

        return self

c1 = C1()

c2 = C2()

(c1.sayHello()).(c2.sayHello())

Output:
hello from c1
hello from c2

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以将其抽象为基类(以避免重复自己),然后,只要他们彼此了解,您就可以近似您最初想要的内容:

class Base(object):

    def sayHello(self, other=None):
        print("hello from {self} to {other}".format(self=self, other=other))
        return other
    def __str__(self):
        return type(self).__name__

class C1(Base):
    '''C1!'''

class C2(Base):
    '''C2!'''

c1 = C1()
c2 = C2()

c1.sayHello(c2).sayHello(c1)

打印:

hello from C1 to C2
hello from C2 to C1

答案 1 :(得分:0)

方法链接通常只能在API中找到,它可以方便地对单个对象执行一系列操作。如何使用两个对象进行操作的问题实际上取决于API或库中的有意义。话虽如此,这里有一个完全抽象的想法:

# Untested code

class OtherChain(object):
    def __init__(self, other=None):
        self._other = other

    def sayHello(self):
        print "hello from {0}".format(type(self).__name__)
        return self._other

class C1(OtherChain):
    pass

class C2(OtherChain):
    pass

c2 = C2()
c1 = C1(c2)

c1.sayHello().sayHello()

# Output:
# hello from C1
# hello from C2

当然,此代码存在问题,因为执行c1.sayHello().sayHello().sayHello()会导致AttributeError(我认为)。如果这个代码在库中有某种更有意义的上下文,那么这些细节可能会得到解决。