0

Let's say I have the following class:

class MyClass: 
    def __init__(self, text):
        self.text = text

    def strip(self):
        strip_text = self.text.strip()

        return strip_text

    def reverse(self):
        rev_text = self.text.strip()[::-1]

        return rev_text

my_name = MyClass('todd ')

I want to able to to call the methods to this class like this:

my_name.strip().reverse()

However, when I do so, it throws an error. How do I go about chaining methods?

6
  • 3
    you need to return self so be able to chain operations, so instead of returning strip_text, set self.strip_text = strip_text and return self Commented Apr 29, 2020 at 19:16
  • This is called a fluent interface. Not as common in Python, although some third-party libraries use it. See this Commented Apr 29, 2020 at 19:17
  • it throws an error Seeing the error would help a lot in tracking down the problem. Commented Apr 29, 2020 at 19:17
  • Does this answer your question? Purpose of return self python Commented Apr 29, 2020 at 19:18
  • my_name.strip() returns an ordinary string, which does not have a .reverse() method. Commented Apr 29, 2020 at 19:19

2 Answers 2

1

my_name.strip() returns a String, which has no reverse() function.

A quick way is just to make my_name.strip() a new Class object, and reverse that:

MyClass(my_name.strip()).reverse()

(However, IMO this is kludgy and there's a better (more pythonic) way to fix this in the Class definition(s) itself.)

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

Comments

0

Each function has to replace the wrapped string, then return self. At the end of the chain, you retrieve the final result.

class MyClass: 
    def __init__(self, text):
        self.text = text

    def strip(self):
        self.text = self.text.strip()

        return self

    def reverse(self):
        self.text = self.text.strip()[::-1]

        return self


my_name.strip().reverse().text

As an alternative to mutating the existing object, a new instance can be returned at each step.

class MyClass: 
    def __init__(self, text):
        self.text = text

    def strip(self):
        return MyClass(self.text.strip())

    def reverse(self):
        return MyClass(self.text.strip()[::-1])

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.