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?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Todd Shannon
  • 527
  • 1
  • 6
  • 20

2 Answers2

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.)

BruceWayne
  • 22,923
  • 15
  • 65
  • 110
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])
chepner
  • 497,756
  • 71
  • 530
  • 681