Python chainable class methods

后端 未结 1 331
小鲜肉
小鲜肉 2021-01-27 23:15

I want to do the following:

pattern = cl().a().b(\"test\").c()

where cl is a class and a, b, c are class methods.

相关标签:
1条回答
  • 2021-01-27 23:29

    Return the class instance at the end of each method and store the intermediate results in a class variable:

    class MyClass:
        result = None
    
        def a(self):
            # do things and store in self.result
            self.result = ...
            return self
    
        def b(self, value):
            # do things and store in self.result
            self.result = ...
            return self
    

    This allows you to chain the methods as desired: cl().a().b("test").c().

    You can then obtain the result by looking at the value of instance.result.

    0 讨论(0)
提交回复
热议问题