Python中的函数链,如果段返回False,则忽略链的其余部分

The title pretty much explains the problem. I don't know if there's a practical solution to this or if I'm being too picky over the behavior of my code. This article was hinting in the right direction, but I never got any code to work. https://medium.com/@adamshort/python-gems-5-silent-function-chaining-a6501b3ef07e

这是我想要的功能的示例:

class Calc:
    def __init__(self, n=0):
        self.n = n

    def add(self, n):
        self.n += n
        return self

    def might_return_false(self):
        return False

    def print(self):
        print(self.n)
        return self


w = Calc()

# The rest of the chain after might_return_false should be ignored
addedTwice = w.add(5).might_return_false().add(5).print()

w.print() # Should print 5

print(addedTwice) # Should print False
评论