Python Tutorial

Showing posts with label Object-oriented programming. Show all posts
Showing posts with label Object-oriented programming. Show all posts

Wednesday, February 20, 2013

Python object-class property

Python object-class property example code
class MyClass(object):
        def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name
        @property
        def name(self):
                return self.first_name +" "+ self.last_name


myClass = MyClass("Abu", "Zahed")
print myClass.name

Output:

Abu Zahed

Tuesday, January 15, 2013

Python getter, setter : access getter, setter as property



All source code available on github

class MyClass(object):
    def __init__(self):
        self.__name = "" # define private variable
        self.__id = 0 # define private variable

    def setName(self, name):
        self.__name = name
    def setId(self, id):
        self.__id = id
    def getName(self):
        return self.__name
    def getId(self):
        return self.__id

    idGS = property(getId, setId) # declare getter, setter property for id

a = MyClass()
a.setName("Python")
a.idGS=5

print "Name ", a.getName()
print "Id ", a.idGS



Output:

Name  Python
Id  5

Python getter, setter example



All source code available on github

class MyClass():
    def __init__(self):
        self.__name = "" # define private variable
        self.__id = 0 # define private variable

    def setName(self, name):
        self.__name = name
    def setId(self, id):
        self.__id = id
    def getName(self):
        return self.__name
    def getId(self):
        return self.__id



a = MyClass()
a.setName("Python")
a.setId(1)


print "Name ", a.getName()
print "Id ", a.getId()

#print a.__name #error
#print a.__id #error


Output:
Name  Python
Id  1

Tuesday, August 28, 2012

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

Thursday, October 28, 2010

Python Threading

'''
    This code use python threading syntax
    - Save this class named 'ThreadClass.py'
'''
import threading
import time

class ThreadClass(threading.Thread):
    def __init__(self,data):
        threading.Thread.__init__(self)
        self.data=data
        
    def run(self):
        for i in range(0,3):
            print "output: ",self.data
            time.sleep(1);

Thursday, August 26, 2010

Python Unzip a tar file

'''
   This class use for Unzip a tar file
'''

import os
import tarfile
import sys

class UnZipFolder():
    def __init__(self, location):
        self.location=location
        # Set output directory here
        self.outputLocation="C:/"

    def decompress(self):
        try:
            if os.path.exists(self.location):
                decompressTar = tarfile.open(self.location)
                decompressTar.extractall(self.outputLocation)
                decompressTar.close()
                print "Extracted"
            else:
                print "No Such Folder"
        except:
            print str(sys.exc_info())
            
if __name__=='__main__':
    # Set input directory here
    location="C:/test.tar"
    unZipFolder=UnZipFolder(location)
    unZipFolder.decompress()

python zip a folder or file



Zip a folder or file is very easy in python. You need to set variable location by your file or folder location.

'''
    This class use for zip a folder
    - Create a folder named "testFolder" on C drive or reset the location
'''

import os
import tarfile
import sys

class ZipFolder():
    # Constructor of ZipFolder
    def __init__(self, location):
        self.location=location

    def makeCompress(self):
        try:
            if os.path.exists(self.location):
                compressTar = tarfile.open(self.location+".tar", "w:gz")
                compressTar.add(self.location)
                compressTar.close()
                print "Compress complete ",self.location
            else:
                print " (ZipFile)No Such Folder ",self.location 
        except:
            print str(sys.exc_info())

if __name__=='__main__':
    location="C:/testFolder"
    zipFolder=ZipFolder(location)
    zipFolder.makeCompress()

Friday, August 20, 2010

python Object-oriented programming : Use existing object

'''
   This code use python class syntax
     - save this class named "MyClass.py" 
'''
class MyClass():
    # Class constructor
    def __init__(self,data):
        self.data=data

    def showSring(self):
        print self.data

    def reverseString(self):
        return self.data[::-1]

if __name__=='__main__':
    myClass=MyClass("Life is very easy Python")
    myClass.showSring()
    print myClass.reverseString()





'''
   This code use class object
     -save this code named "AnyName.py"
'''
import MyClass

class MyClassUser():
    def __init__(self,data):
        self.data=data
        self.myClass=MyClass.MyClass(self.data)
        
    def callMyClass(self):
        self.myClass.showSring()
        print self.myClass.reverseString()
        
if __name__=="__main__":
    myClassUser=MyClassUser("Life is very easy with Python")
    myClassUser.callMyClass()




Must save class "Myclass.py" and "AnyName.py" in same folder then run "AnyName.py"



Output:
Life is very easy with Python
nohtyP htiw ysae yrev si efiL

python Object-oriented programming

'''
   This code use python class syntax
     - save this class named "MyClass.py" 
'''
class MyClass():
    # Class constructor
    def __init__(self,data):
        self.data=data

    def showSring(self):
        print self.data

    def reverseString(self):
        return self.data[::-1]

if __name__=='__main__':
    #declare object
    myClass=MyClass("Life is very easy Python")
    #use object
    myClass.showSring()
    print myClass.reverseString()




Output:
Life is very easy Python
nohtyP ysae yrev si efiL