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

Python-在字典中声明方法名称,并在类外声明方法定义,python,Python,我想定义一个引用方法的字典,但方法定义不在字典定义的范围内 目前,我得到一个名称错误:名称“method1”未定义 为了澄清,我看到了定义函数的示例,然后在同一范围内创建了使用函数名的字典,但这不是我想要做的。您需要将字典指向实际方法: from foo import fooClass dict = {'a': method1, 'b': method2} bar = fooClass() method = dict['a'] bar.method() 由于method1未在该范围内定

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

目前,我得到一个名称错误:名称“method1”未定义


为了澄清,我看到了定义函数的示例,然后在同一范围内创建了使用函数名的字典,但这不是我想要做的。

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

from foo import fooClass

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

bar = fooClass()

method = dict['a']

bar.method()
由于
method1
未在该范围内定义,因此需要引用
fooClass
类上的方法


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

from foo import fooClass

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

谢谢,效果很好。我曾考虑过定义一个类的实例,但后来我不得不将其传递给其他人,并认为必须有更好的方法。完美答案@用户3089611如果有帮助,您可以单击绿色勾号接受此答案,以向搜索答案的其他用户表明您对您的问题有可接受的答案。再次感谢。我已经在stackexchange上读了很长一段时间了,我想这是我的第一篇文章,所以谢谢你的提醒。
from foo import fooClass

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

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