简体   繁体   English

在 Python 中为类动态添加方法

[英]Dynamically adding methods to a class in Python

I'm trying to add methods to a class based on a list.我正在尝试根据列表向类添加方法。

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)

The problem is that when I call _Roles.dev() , _Roles.stage() , or _Roles.prod() , I always get printed the last step that is prod instead of getting dev for dev() and so on.问题是,当我调用_Roles.dev()_Roles.stage()_Roles.prod() ,我总是会打印prod的最后一步,而不是为dev()获取dev等等。 what's the reason for this?这是什么原因?

Because you use the same scope for all function declarations .因为您对所有函数声明使用相同的作用域 Define each function in a separate scope.在单独的作用域中定义每个函数。

Just use setattr :只需使用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()

Output :输出 :

self.v = 5自我.v = 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM