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. what's the reason for this?
Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator “+” in Python.
Just use 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With