0

I want to do the following:

pattern = cl().a().b("test").c()

where cl is a class and a, b, c are class methods.

After that I need to call pattern.to_string and it should output a string that was formed. Each method returns a string.

Now how can I achieve the above? Append the method output to a list? What about the chainable function? If I wrote the class the normal way, the above won't work.

Thank.

3
  • What do you mean "the normal way"? What have you tried so far, and in what way did it not work? Commented Nov 4, 2013 at 0:31
  • “Each method returns a string” – That’s not how that works. Commented Nov 4, 2013 at 0:31
  • @poke that's why I'm asking on stackoverflow. I wasn't exactly sure how should I implement chainable functions. Commented Nov 4, 2013 at 0:34

1 Answer 1

4

Return the class instance at the end of each method and store the intermediate results in a class variable:

class MyClass:
    result = None

    def a(self):
        # do things and store in self.result
        self.result = ...
        return self

    def b(self, value):
        # do things and store in self.result
        self.result = ...
        return self

This allows you to chain the methods as desired: cl().a().b("test").c().

You can then obtain the result by looking at the value of instance.result.

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

1 Comment

Oh I see. Thank you!! I'll accept your solution when it's possible after 10 minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.