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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…