Skip to main content
 首页 » 编程设计

python之python类中方法的动态分配

2025年05月04日16mengfanrong

我想在类 __init__ 方法中动态创建一堆方法。到目前为止还没有运气。

代码:

class Clas(object): 
    def __init__(self): 
        for i in ['hello', 'world', 'app']: 
            def method(): 
                print i 
            setattr(self, i, method) 

然后我创建适合列表的方法和调用方法。

>> instance = Clas() 
 
>> instance.hello() 
 
'app' 

我希望它打印hello 而不是app。问题是什么? 此外,即使我执行 copy.copy(method)

,这些动态分配的方法中的每一个都引用了内存中的相同函数

请您参考如下方法:

您需要正确绑定(bind)i:

for i in ['hello', 'world', 'app']: 
    def method(i=i): 
        print i 
    setattr(self, i, method) 

然后 i 变量成为 method 的本地变量。另一种选择是使用新范围(单独的函数)生成您的方法:

def method_factory(i): 
    def method(): 
        print i 
    return method  
 
for i in ['hello', 'world', 'app']: 
    setattr(self, i, method_factory(i))