I have two files. In the first there is a dictionary ready for export:
__all__ = ['container']
def show_name(self):
myFunction()
print self.name
container = {
'show_name': show_name
}
In the second file I import myFunction and I define the class Person:
from myModule import myFunction
class Person:
def __init__(self):
self.name = 'Bob'
self.show_name = types.MethodType(container['show_name'], self)
person = Person()
The problem is that when I call person.show_name() I get the error:
NameError: global name ‘myFunction’ is not defined
How can I have Person.show_name access the same functions Person does?
Move
from myModule import myFunctionto the same file whereshow_nameis defined.By the way,
makes
('show_name',<bound_method>)a key-value pair inself.__dict__. That causes every instance of Person to get a new, independent key-value pair.To save memory, you might want to change that to Roman Bodnarchuk other solution.