Skip to content Skip to sidebar Skip to footer

Calling Chains Methods With Intermediate Results

I have a class and some methods of it. Could I keep a result of the methods between calling. Example calling: result = my_obj.method_1(...).method_2(...).method_3(...) when me

Solution 1:

There is a pretty straightforward pattern called the Builder Pattern where methods basically return a reference to the current object, so that instead of chaining method calls on one another they are chained on the object reference.

The actual Builder pattern described in the Gang of Four book is a little verbose (why create a builder object) instead just return a reference to self from each setXXX() for clean method chaining.

That could look something like this in Python:

classPerson: defsetName(self, name):
      self.name = name
      returnself## this is what makes this workdefsetAge(self, age):
      self.age = age;
      returnself;

   defsetSSN(self, ssn):
      self.ssn = ssn
      returnself

And you could create a person like so:

p = Person()
p.setName("Hunter")
 .setAge(24)
 .setSSN("111-22-3333")

Keep in mind that you will actually have to chain the methods with them touching p.a().b().c() because Python doesn't ignore whitespace.

As @MaciejGol notes in the comments you can assign to p like this to chain with whitespace:

p = (
   Person().setName('Hunter')
           .setAge(24)
           .setSSN('111-22-3333')
)

Whether or not this is the best style/idea for Python I can't say, but this is sort of how it would look in Java.

Solution 2:

There are multiple choices which would entirely depend on your complete scenario -

  1. Chain of Responsibility - If your different classes needs to follow a chain of operations.
  2. Decorator - When you dont know which sequence you need to top up your class object with additional features
  3. Builder - which would help you to assign parameter values to your class.

Post a Comment for "Calling Chains Methods With Intermediate Results"