from foo import fooClass
dict = {'a': method1, 'b': method2}
bar = fooClass()
method = dict['a']
bar.method()
I want to define a dictionary with a reference to a method but the method definition is not in the scope of the dictionary definition.
Currently, I get a NameError: name 'method1' is not defined.
To clarify, I have seen examples where functions are defined, then a dictionary using the function names is created in the same scope but this is not what I want to do.
You need to point the dictionary to the actual method:
from foo import fooClass
dict = {'a': fooClass.method1, 'b': fooClass.method2}
Since method1
isn't defined in that scope, you need to reference the method on the fooClass
class.
Alternatively, if you didn't want to have to keep referening fooClass
in your code, you could store the methods as strings and use getattr()
do to this:
from foo import fooClass
dict = {'a': 'method1', 'b': 'method2'}
bar = fooClass()
method = getattr(bar.__class__, method = dict['a'])
bar.method()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments