Python可链接类方法 [英] Python chainable class methods
问题描述
我要执行以下操作:
pattern = cl().a().b("test").c()
其中 cl
是一个类,而 a,b,c
是类方法.
where cl
is a class and a, b, c
are class methods.
在那之后,我需要调用 pattern.to_string
,它应该输出一个已形成的字符串.每个方法都返回一个字符串.
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.
谢谢.
推荐答案
在每个方法的末尾返回类实例,并将中间结果存储在类变量中:
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
这允许您根据需要链接方法: cl().a().b("test").c()
.
This allows you to chain the methods as desired: cl().a().b("test").c()
.
然后您可以通过查看 instance.result
的值来获得结果.
You can then obtain the result by looking at the value of instance.result
.
这篇关于Python可链接类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!