我在TestClass
对象的python程序中有一个方法链,如下所示:
TestClass().method1(args).method2(args).method3(args)
我想建立一个实用程序,它将扫描上述链,然后它可以建立一个执行序列。(类似于数据处理框架构建其执行图或dag的方式)。而且,直到我在最后调用run()
,上面的序列才会运行。
因此,在我的例子中,只有当run()
方法被添加到链的末尾时,它才会运行。
TestClass().method1(args).method2(args).method3(args).run()
如何做到这一点?
发布于 2018-07-14 17:28:45
你想要的是一个流畅的界面。
我将给你一个简单的例子,用某种装饰器可以使它变得更好
class A:
def __init__(self):
self.call_chain = []
def m1(self, arg):
def _actual_logic():
print(arg)
self.call_chain.append(actual_logic)
return self
def run(self):
for f in self.call_chain:
f()
a = A().m1('snth')
a.run()
发布于 2018-07-14 16:43:13
我从这个answer中得到了灵感,以便详细阐述我的。
因此,我将使用inspect
和re
模块以及一个decorator
来检查是否调用了run
方法:
import re
import inspect
def check_run_is_called(func):
def wrapper(*args, **kwargs):
# Here the interesting part
# We're searching if the string `.run()` exists in the code context
run_exist = re.search(r'\.run\(.*?\)', inspect.stack()[-1].code_context[0])
if not run_exist:
raise Exception('Run must be called !')
f = func(*args, **kwargs)
return f
return wrapper
class TestClass():
@check_run_is_called
def method1(self, arg):
print(arg)
return self
@check_run_is_called
def method2(self, arg):
print(arg)
return self
@check_run_is_called
def method3(self, arg):
print(arg)
return self
def run(self):
print('Run')
# test
if __name__ == '__main__':
app = TestClass()
app.method1('method1').method2('method2').method3('method3').run()
输出:
method1
method2
method3
Run
否则,如果我们调用方法链而不包含run
方法:
app.method1('method1').method2('method2').method3('method3')
我们会得到一个Exception
Exception: Run must be called !
除此之外,您还可以像下面这样创建链的组合:
app.method1('method1').run()
# method1
# Run
app.method1('method1').method2('method2').run()
# method1
# method2
# Run
app.method2('method2').method3('method3').method1('method1').run()
# method2
# method3
# method1
# Run
https://stackoverflow.com/questions/51336374
复制相似问题