我有一个数据字典,关键是文件名,值是其属性值的另一个字典.现在我想将这个数据结构传递给各种函数,每个函数都对属性进行一些测试并返回True / False.
一种方法是从主代码中明确地逐个调用每个函数.但是我可以这样做:
#MYmodule.py
class Mymodule:
def MYfunc1(self):
...
def MYfunc2(self):
...
#main.py
import Mymodule
...
#fill the data structure
...
#Now call all the functions in Mymodule one by one
for funcs in dir(Mymodule):
if funcs[:2]=='MY':
result=Mymodule.__dict__.get(funcs)(dataStructure)
这种方法的优点是当我向MYmodule添加更多逻辑/测试时,主类的实现不需要改变.
这是解决手头问题的好方法吗?这个解决方案有更好的替代方案吗?
最佳答案 我会说更好更多的Pythonic方法是定义一个
decorator以指示你想要使用哪些函数:
class MyFunc(object):
funcs = []
def __init__(self, func):
self.funcs.append(func)
@MyFunc
def foo():
return 5
@MyFunc
def bar():
return 10
def quux():
# Not decorated, so will not be in MyFunc
return 20
for func in MyFunc.funcs:
print func()
输出:
5
10
基本上,您执行相同的逻辑:仅采用以特定方式定义的函数,并将它们应用于特定的数据集.