1

I know how to implement method chaining in Python within a single class, but I'm wondering if there is a way to chain methods from different classes, something like:

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

Any ideas?

5
  • 1
    what are you trying to accomplish here? like why? have you tried running it? Commented Oct 23, 2014 at 15:37
  • Yeh I tried, obviously it doesn't work. My goal is to chain methods from different classes. Commented Oct 23, 2014 at 15:39
  • +1, You can do it, as long as your methods return the other object. See my answer. Commented Oct 23, 2014 at 15:42
  • I see someone voted to close, but I think it's quite clear what was being asked. Is there anything further I can answer? Commented Oct 23, 2014 at 16:04
  • Thanks, your answer makes me understand how to proceed. Commented Oct 23, 2014 at 16:07

2 Answers 2

2

You can abstract this into a base class (to avoid repeating yourself) and then, as long as they know each other, you can approximate what you originally wanted:

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)

prints:

hello from C1 to C2
hello from C2 to C1
Sign up to request clarification or add additional context in comments.

Comments

0

Method chaining is usually only found in APIs where it makes it convenient to perform a sequence of actions on a single object. The question of how to do it with two objects would really depend on how that was meaningful in your API or library. That being said, here's one idea which is completely abstract:

# 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

Of course this code has issues since doing c1.sayHello().sayHello().sayHello() would cause an AttributeError (I think). Those kinds of details would probably get worked out if this code had some kind of context in a library where it was more meaningful.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.