Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

python - 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 method_v3(...) received a result from the method_2(..) who received a result from the method 1(..)

Please tell me, are there patterns or anything to decide above example?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...