Python chainable class methods

孤者浪人 提交于 2021-02-05 09:39:19

问题


I want to do the following:

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

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

After that I need to call pattern.to_string and it should output a string that was formed. Each method returns a string.

Now how can I achieve the above? Append the method output to a list? What about the chainable function? If I wrote the class the normal way, the above won't work.

Thank.


回答1:


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.



来源:https://stackoverflow.com/questions/19759969/python-chainable-class-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!