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

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

Tuesday, August 28, 2012

Python public and private class



Sometimes we need to make class public and private also.

Lets see python syntex how to do it



 
#privateClassSample.py

class MyClass(): def myPublicFunction(self): print "I am public function" def __myPrivateFunction(self): print "I am private function" class _MyPrivateClass(): def myPrivateFunction(self): print "I am private function of class _MyPrivateClass"


 
#test.py

from privateClassSample import * a=MyClass() a.myPublicFunction() #b=_MyPrivateClass() # this willl not work, _MyPrivateClass is private class


Output:
I am public function


Python class public method and private method



Sometimes we need to make some private and public function for a class.
Lets see python syntex for such class


 
#publicVsPrivate.py
class MyClass(): def myPublicFunction(self): print "I am public function" def __myPrivateFunction(self): print "I am private function" myClass= MyClass() myClass.myPublicFunction() #myClass.__myPrivateFunction # This is will not work, __myPrivateFunction private method


Output:
I am public function

Python static method and class method



Both meythod have some similarities, we can use them without instantiate the object.
Static method know nothing about class and class method knows.
Lets go to a example code:


 
#staticVsClassMethod.py
class MyClass(): def anyFunction(self): print "I am any function" @staticmethod def myStaticFunction(): print "I am static method" @classmethod def myClassFunction(cls): print "I am class method" print cls MyClass.myStaticFunction() MyClass.myClassFunction() #MyClass.anyFunction() #this is not possible, need a object instance


Output:
I am static method
I am class method
__main__.MyClass

Wednesday, August 15, 2012

python extending class



Sometimes we need to extend an existing class, lets do it some python way


#speak.py
class Speak(object):
    def __init__(self,tone):
        self.tone = tone
    def getTone(self):
        print self.tone



#anyName.py
from speak import Speak

class Bird(Speak):
    def __init__(self,birdTone):
        #construct super class
        Speak.__init__(self,birdTone)


class Cow(Speak):
    def __init__(self,cowTone):
        #another way to construct super class
        super(Cow, self).__init__(cowTone)
       

bird= Bird("Bird Talk")
bird.getTone()

cow= Cow("Cow Talk")
cow.getTone()



Output:
Bird Talk
Cow Talk

Sunday, August 12, 2012

Python object comparison



Sometimes we need to compare between to object of same class. It is very easy in python


class MyClass():
    def __init__(self,p,q,r):
        self.a=p
        self.b=q
        self.c=r
        
    def __eq__(self,other): 
        return self.__dict__ == other.__dict__

objA=MyClass("AA",2,3)
objB=MyClass("AA",2,3)
objC=MyClass("AA",2,6)

print objA == objB
print objA == objC



Output:
True
False



You can also make customize comparison, compare some part of object


class MyClass():
    def __init__(self,p,q,r):
        self.a=p
        self.b=q
        self.c=r
        
    def __eq__(self,other): 
        return self.b == other.b and self.c == other.c

objA=MyClass("AEA",2,3)
objB=MyClass("AA",2,3)
objC=MyClass("AA",2,6)

print objA == objB
print objA == objC



Output:
True
False