我知道如何在单个类中实现 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/