I found this method chaining in python, but even with it I couldn't understand method chaining in Python.
Here the goals are two: solve the coding problem and understand method chaining (given that I am still not 100% confident with callables).
Down to the problem definition.
I want a class that has two methods: one sets a parameter of the object = 'line' and the other overwrites to 'bar'.
This is what I got so far:
class foo():
def __init__(self, kind=None):
self.kind = kind
def __call__(self, kind=None):
return foo(kind=kind)
def my_print(self):
print (self.kind)
def line(self):
return self(kind='line')
def bar(self):
return self(kind='bar')
Sadly, with this code I can achieve my goal doing this
a = foo()
a.bar().line().bar().bar().line().my_print()
But I would like to obtain the same result by writing this code
a = foo()
a.bar.line.bar.bar.line.my_print()
How do I achieve this? I guess is something wrong in how I defined the __call__
method. Thanks in advance for your help.