[英]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.