连锁动态调用功能

时间:2019-06-20 19:03:26

标签: python python-3.x

我试图在链中动态调用函数。我可以通过引用类和函数名来使它工作,但我正在尝试使其更加动态。有什么想法吗?

testFunctions.py

class TestFunctions(object):
    def __init__(self, name=None):
        self.name = name

    def test1(self, **param1):
        print('inside test1() with args:'+str(param1))
        return param1.get('param1'), 'xyz'

    def test2(self, param1, param2):
        print('inside test2() with args:'+param1+','+param2)
        return 'test2'


    def test3(self, param1):
        print('inside test3() with args:'+param1)
        return "Hello"

有效的测试代码:

from testFunctions import TestFunctions

param1 = {}
param1['param1'] = 'ABCD'
tClass = TestFunctions()
output = tClass.test3(tClass.test2(*tClass.test1(**param1)))
print(output)

测试代码以使其动态,其工作原理与上述测试类似:

from testFunctions import TestFunctions
param1 = {}
param1['param1'] = 'ABCD'
tClass = TestFunctions()
funcList = ['test3', 'test2', 'test1']
for funcName in funcList:
    func = getattr(tClass, funcName)
    func()

1 个答案:

答案 0 :(得分:2)

由于您在功能上有一定的灵活性,因此可以对其进行调整,使它们都具有相同的签名。到底是什么无关紧要,但是如果您能以相同的方式全部使用它们,并且上一个函数提供了下一个函数的预期参数,那么一切将变得更加容易。

例如,在我更改功能的地方,所以都使用单个参数调用了所有函数—可以是元组,字典或单个缩放器。这样,放入循环或reduce()中就很简单了:

class TestFunctions(object):
    def __init__(self, name=None):
        self.name = name

    def test1(self, param): # expects a mapping
        print('inside test1() with args:'+str(param))
        return param1.get('param1'), 'xyz'

    def test2(self, params): # expects a sequence
        print('inside test2() with args:'+params[0]+','+params[1])
        return 'test2'

    def test3(self, param): # scalar value
        print('inside test3() with args:'+param)
        return "Hello"

from functools import reduce

tClass = TestFunctions()
funcList = ['test1', 'test2', 'test3']
val = {'param1': 'ABCD'}

for f in funcList:
    val =  getattr(tClass, f)(val)
print(val)

结果:

inside test1() with args:{'param1': 'ABCD'}
inside test2() with args:ABCD,xyz
inside test3() with args:test2
Hello