所以我在某处看到了这段代码。
1] 那么为什么我们在每个方法结束时都返回 self 呢?它的目的是什么?
2] 如何解释方法链接(最后一行)- doug.set_legs(4).count_legs().sleep().sleep().sleep()
class pet:
number_of_legs = 0
def sleep(self):
print "zzz "
return self
def set_Legs(self, legs):
self.number_of_legs = legs
return self
def count_legs(self):
print "I have %s legs" % self.number_of_legs
return self
class dog(pet):
def bark(self):
print "Woof"
doug = dog()
doug.set_Legs(4).count_legs().sleep().sleep().sleep() # Any explanation for this chaining & how its operating particularly in this case ??
>>>I have 4 legs
ZZZ
ZZZ
ZZZ
Out[249]: <__main__.dog instance at 0x7fd5d81917e8> # Why & from where this part getting printed ??
doug.set_legs(4).count_legs().sleep().set_legs(10).count_legs().sleep().sleep()
>>>I have 4 legs
ZZZ
I have 10 legs
ZZZ
ZZZ
Out[242]: <__main__.dog instance at 0x7fd5d81917e8> # Why & from where this part getting printed ??