动态调用函数Python

2024-10-03 02:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数列表。。。e、 g

def filter_bunnies(pets): ...

def filter_turtles(pets): ...

def filter_narwhals(pets): ...

有没有一种方法可以通过使用代表函数名称的字符串来调用这些函数?

例如

^{pr2}$

Tags: 方法函数字符串名称列表def代表filter
3条回答

你的函数是对象的一部分吗?如果是这样,您可以使用^{}函数:

>> 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')

相关问题 更多 >