Python Tutorial

Friday, August 31, 2012

Python dynamically add class attribute



Dynamically add attribute of a class is very easy in python. And it is useful to know.
Here I have a class named Arithmetic, now I want to add functionality of this class named addNum which perform add two number.
Lets see the example


 
class Arithmetic(object):
    pass

def arithmetic_function_add(cls):
    def sampleFunction(self,a,b):
        return a+b
    sampleFunction.__name__ = "addNum"
    setattr(cls,sampleFunction.__name__,sampleFunction)

arithmetic_function_add(Arithmetic)

arithmetic=Arithmetic()
print arithmetic.addNum(5,6)




Output:
11

0 comments:

Post a Comment