3

In python, is it possible to chain together class methods and functions together? For example, if I want to instantiate a class object and call a method on it that affects an instance variable's state, could I do that? Here is an example:

class Test(object):
    def __init__(self):
        self.x = 'Hello'

    @classmethod
    def make_upper(y):
        y.x = y.x.upper()

What I'm wanting to do is this:

h = Test().make_upper()

I want to instantiate a class object and affect the state of a variable in one line of code, but I would also like to be able to chain together multiple functions that can affect state or do something else on the object. Is this possible in python like it is in jQuery?

4
  • 2
    If each method you call returns the object that provides the next method you want to call, it will work. If they don't, it won't. It depends how your methods are written. Commented Jul 4, 2018 at 14:47
  • 1
    If all your methods return self, sure Commented Jul 4, 2018 at 14:47
  • Generally not good design, but if it works for you, it works for you. Commented Jul 4, 2018 at 14:48
  • 3
    Also, you probably don't want make_upper to be a classmethod. Commented Jul 4, 2018 at 14:49

2 Answers 2

5

Yes, sure. Just return self from the instance methods you are interested in:

class Test(object):
    def __init__(self):
        self.x = 'Hello'

    def make_upper(self):
        self.x = self.x.upper()
        return self
    def make_lower(self):
        self.x = self.x.lower()
        return self

h = Test().make_upper()
print(h.x)

Output:

HELLO
Sign up to request clarification or add additional context in comments.

Comments

2

Yes and no. The chaining certainly works, but h is the return value of make_upper(), not the object returned by Test(). You need to write this as two lines.

h = Test()
h.make_upper()

However, PEP-572 was recently accepted for inclusion in Python 3.8, which means someday you could write

(h := Test()).make_upper()

The return value of Test() is assigned to h in the current scope and used as the value of the := expression, which then invokes its make_upper method. I'm not sure I would recommend using := in this case, though; the currently required syntax is much more readable.

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.