Python Tutorial

Showing posts with label dynamic code execution. Show all posts
Showing posts with label dynamic code execution. Show all posts

Monday, September 3, 2012

Python eval example code



Python eval evaluate expression, not statement. Let's see a example


 
v=5
print v
v=eval("v+5")
print v
#eval("print v") #It will not work



Output:
5
10

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

python dynamic code execution, exec exaqmple



Dynamic code execution is very important in some cases. Sometimes we need to generate code dynamically and then run it. Lets see a very simple example using exec:


 
v=5

code = """def myFun():
            global v
            v=10
            print 'This is my function'
       """
exec code

print v
myFun() #must execute the code before calling function
print v



Output:
5
This is my function
10