您似乎想要一种无需太多复杂代码即可迭代一组函数的方法。
我建议创建一个将所有方法捆绑在一起的类,如下所示:
class Calculator():
"""Container class for functions over which to iterate and/or access with strings."""
def __init__(self):
pass
def list_calc_funcs(self):
"""returns list of functions starting with 'calc_', uncalled"""
return [getattr(self, name) for name in self.list_calc_names()]
def list_calc_names(self):
"""returns list of unique part of strings identifying 'calc_' functions"""
return [string for string in dir(self) if string[:5]=='calc_']
def calculate(self,cnt:str,*args,**kwargs):
"""calls a 'calc_' function using a string"""
try:
calc = getattr(self,"calc_" + cnt)
except AttributeError:
raise ValueError("The named function does not exist.")
return calc(*args,**kwargs)
def calc_foo(self,*args,**kwargs):
pass
def calc_bar(self,*args,**kwargs):
pass
def calc_1(self,*args,**kwargs):
pass
def calc_2(self,*args,**kwargs):
pass
C = Calculator()
它的工作方式是利用“dir()”和“getattr()”。 dir() 基本上返回一个包含所有实例变量名称的列表,包括任何函数。
例如,如果您调用 dir(C),它将返回:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'calc_1',
'calc_2',
'calc_bar',
'calc_foo',
'calculate',
'list_calc_funcs',
'list_calc_names']
这使您可以使用基本的字符串方法来查找所需的方法,只需使用您喜欢的任何命名方案“标记”它们。
getattr(object,attribute_name) 是一个非常有用的知识,它允许您使用字符串访问几乎任何东西的属性/变量/方法。如果您需要让用户能够根据字符串指定函数,或者如果您需要遍历 dir() 中的某些值,它非常强大。
在 list_calc_names() 中,我使用列表推导轻松地返回所有以“calc_”开头的属性名称。请注意,如果您这样做,您需要确保不要以这种方式启动任何变量名,否则它们也会被返回。就我而言,它返回:
['calc_1', 'calc_2', 'calc_bar', 'calc_foo']
在 list_calc_funcs() 中,我再次使用列表推导来迭代 list_calc_names() 的结果并返回函数本身。它返回:
[<bound method Calculator.calc_1 of <__main__.Calculator object at 0x000000000A12E0D0>>,
<bound method Calculator.calc_2 of <__main__.Calculator object at 0x000000000A12E0D0>>,
<bound method Calculator.calc_bar of <__main__.Calculator object at 0x000000000A12E0D0>>,
<bound method Calculator.calc_foo of <__main__.Calculator object at 0x000000000A12E0D0>>]
函数“calculate()”展示了如何根据可以在运行时输入的字符串而不是直接调用函数来概括调用特定函数。