Python在字典中声明方法名,方法定义在类外

2024-04-20 01:35:44 发布

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

from foo import fooClass

dict = {'a': method1, 'b': method2}

bar = fooClass()

method = dict['a']

bar.method()

我想定义一个引用方法的字典,但方法定义不在字典定义的范围内。你知道吗

当前,我得到一个NameError:名称“method1”未定义。你知道吗

为了澄清这一点,我看过一些例子,其中定义了函数,然后在同一范围内创建了一个使用函数名的字典,但这不是我想做的。你知道吗


Tags: 方法函数fromimport名称字典定义foo
1条回答
网友
1楼 · 发布于 2024-04-20 01:35:44

您需要将字典指向实际方法:

from foo import fooClass

dict = {'a': fooClass.method1, 'b': fooClass.method2}

由于method1未在该范围内定义,因此需要引用fooClass类上的方法。你知道吗


或者,如果不想在代码中一直引用fooClass,可以将方法存储为字符串,并使用getattr()执行以下操作:

from foo import fooClass

dict = {'a': 'method1', 'b': 'method2'}

bar = fooClass()
method = getattr(bar.__class__, method = dict['a'])
bar.method()

相关问题 更多 >