我想__init__动态地在类方法中创建一堆方法.到目前为止还没有运气.
码:
class Clas(object):
def __init__(self):
for i in ['hello', 'world', 'app']:
def method():
print i
setattr(self, i, method)
Run Code Online (Sandbox Code Playgroud)
比我列表中最适合的方法和调用方法.
>> instance = Clas()
>> instance.hello()
'app'
Run Code Online (Sandbox Code Playgroud)
我希望它打印hello不app.问题是什么?此外,这些动态分配的方法中的每一个都在内存中引用相同的功能,即使我这样做copy.copy(method)
你需要i正确绑定:
for i in ['hello', 'world', 'app']:
def method(i=i):
print i
setattr(self, i, method)
Run Code Online (Sandbox Code Playgroud)
然后i变量是本地的method.另一个选择是使用生成方法的新范围(单独的函数):
def method_factory(i):
def method():
print i
return method
for i in ['hello', 'world', 'app']:
setattr(self, i, method_factory(i))
Run Code Online (Sandbox Code Playgroud)