Calling circuit methods with intermediate results

I have a class and some of its methods. Can I save the result of methods between calls.

Call example:

result = my_obj.method_1 (...). method_2 (...). method_3 (...)

when method_v3(...) got the result from method_2(..) , which got the result from method 1(..)

Please tell me if you have templates or something else?

+6
source share
2 answers

There is a fairly simple template called Builder Pattern , where the methods basically return a link to the current object, so that instead of chaining calls to each other, they are linked by a link to the object.

The actual Builder template described in the Gang of Four book is a bit detailed (why create a builder), instead just return a self reference from each setXXX() for a clean chain of methods.

In Python, it might look something like this:

 class Person: def setName(self, name): self.name = name return self ## this is what makes this work def setAge(self, age): self.age = age; return self; def setSSN(self, ssn): self.ssn = ssn return self 

And you can create such a person:

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

Keep in mind that you really need to associate methods with them by touching pa().b().c() , because Python does not ignore spaces.

As @MaciejGol notes in the comments, you can assign p as a chain with spaces:

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

I cannot say that this is the best style / idea for Python, but it is similar to how it will look in Java.

+7
source

There are several options that completely depend on your complete scenario -

  • Chain of Responsibility - If your different classes should follow a chain of operations.
  • Decorator - When you do not know in what sequence you need to replenish your class object with additional functions
  • Builder - this will help you assign parameter values ​​to your class.
0
source

Source: https://habr.com/ru/post/1213405/


All Articles