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

标签 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

有什么想法吗?

最佳答案

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

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

关于Python - 方法链接来自不同类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26531730/

相关文章:

python - 分类器超参数之间的相关性

scala - 实现支持方法链的Scala特性的最佳实践

python - TableFactory PDFTable 仅输出列标题

python - 在多个文本文件中搜索两个字符串?

python - 将具有 multiindex 的 Pandas 数据框除以另一个具有较小 multiindex 的数据框

python - 将文本字符串 K & M 转换为 10^3 & 10^6

javascript - 来自字符串的链式方法

php - 在 PHP 中链接方法并将第一个调用的方法作为最后一个执行,它是如何工作的?

php - 检查调用是否是方法链接

asp.net - 使用 HtmlTextWriter 呈现服务器控件?