Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding methods to a class in Python

Tags:

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. what's the reason for this?

like image 470
Oscar Yañez Avatar asked Oct 26 '12 00:10

Oscar Yañez


People also ask

How do you dynamically create a class object in Python?

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.

What is __ add __ method in Python?

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.


1 Answers

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

like image 199
Ismael EL ATIFI Avatar answered Sep 18 '22 10:09

Ismael EL ATIFI