我有两个文件。第一个是准备出口的字典:
__all__ = ['container']
def show_name(self):
myFunction()
print self.name
container = {
'show_name': show_name
}
在第二个文件中,我导入myFunction
并定义了类Person
:
from myModule import myFunction
class Person:
def __init__(self):
self.name = 'Bob'
self.show_name = types.MethodType(container['show_name'], self)
person = Person()
问题在于,当我拨打person.show_name()
时,我收到错误:
NameError:未定义全局名称'myFunction'
我如何Person.show_name
访问相同的功能Person
?
答案 0 :(得分:2)
将from myModule import myFunction
移至定义show_name
的同一文件。
顺便说一下,
class Person:
def __init__(self):
self.name = 'Bob'
self.show_name = types.MethodType(container['show_name'], self)
在('show_name',<bound_method>)
中使self.__dict__
成为键值对。这会导致Person的每个实例获得一个新的独立键值对。
要节省内存,您可能需要将其更改为Roman Bodnarchuk other solution。
class Person:
show_name = container['show_name']
def __init__(self):
self.name = 'Bob'