2024-10-03 02:42:01 发布
网友
我有一个函数列表。。。e、 g
def filter_bunnies(pets): ... def filter_turtles(pets): ... def filter_narwhals(pets): ...
有没有一种方法可以通过使用代表函数名称的字符串来调用这些函数?
例如
你的函数是对象的一部分吗?如果是这样,您可以使用^{}函数:
>> class A: def filter_bunnies(self, pets): print('bunnies') >>> getattr(A(), 'filter_bunnies')(1) bunnies
可以,您可以使用:
globals()['filter_bunnies']()
叫“过滤兔”。在
您可以使用内置函数locals()来获取变量和函数的字典,下面是一个示例:
def a(str): print("A" + str) def b(str): print("B" + str) def c(str): print("C" + str) for f in ['a', 'b', 'c']: locals()[f]('hello')
你的函数是对象的一部分吗?如果是这样,您可以使用^{} 函数:
可以,您可以使用:
叫“过滤兔”。在
您可以使用内置函数locals()来获取变量和函数的字典,下面是一个示例:
相关问题 更多 >
编程相关推荐