8

我正在尝试将方法添加到基于列表的类中。

class _Roles(object):
    """
    set the roles for dev, staging and production
    """
    def __init__(self):
        from types import MethodType
        steps = ['dev','stage','prod']
        for step in steps:
            def env_setter(self):
                print step
            method = MethodType(env_setter,self,self.__class__)
            setattr(self,step,method)

问题是,当我调用_Roles.dev()_Roles.stage()或时_Roles.prod(),我总是会打印出prod的最后一步,而不是得到devdev()等等。这是什么原因?

4

2 回答 2

9

只需使用setattr

class Foo:
    def __init__(self, v):
        self.v = v
        
def my_new_method(self):
    print("self.v =", self.v)

setattr(Foo, 'print_v', my_new_method)

Foo(5).print_v()

输出 :

自我.v = 5

于 2021-01-04T23:18:27.337 回答
3

因为您对所有函数声明使用相同的范围。在单独的范围内定义每个函数。

于 2012-10-26T00:39:20.987 回答