Python Tutorial

Wednesday, September 26, 2012

Python best free resources

Here I found some python cool tutorials and books for free. It is keeping me awake late night.
http://pythonbooks.revolunet.com/
You may share yours

Monday, September 17, 2012

Design pattern in python: Abstract factory pattern



Abstract factory pattern in python.


 
class Shop(object):
    def __init__(self, item_factory = None):
        self.item_factory=item_factory

    def get_item_description(self):
        item=self.item_factory.get_item()
        print "Item model ",self.item_factory.model()
        print "Item name ",item.name()
        print "Item color ",self.item_factory.color()

class Shoes(object):
    def name(self):
        return "Shoes"
    def __str__(self):
        return "Shoes"

class Mobile(object):
    def name(self):
        return "Nokia"
    def __str__(self):
        return "Nokia"

class ShoesFactory(object):
    def get_item(self):
        return Shoes()
    def model(self):
        return "MEN101"
    def color(self):
        return "Black"

class MobileFactory(object):
    def get_item(self):
        return Mobile()
    def model(self):
        return "NOK404"
    def color(self):
        return "Black deep"

shopShoes=Shop(ShoesFactory())
shopShoes.get_item_description()
print "*"*30
shopMobile=Shop(MobileFactory())
shopMobile.get_item_description()



Output:
Item model  MEN101
Item name  Shoes
Item color  Black
******************************
Item model  NOK404
Item name  Nokia
Item color  Black deep

Design pattern in python: Singleton pattern



Python singleton design pattern example:
For implementing Singleton pattern we need to override the "__new__" method of class


class MyClass:
 def __init__(self):
  self.numA = 5
  self.numB = 10
 
 def getNumA(self):
  return self.numA

 def getNumB(self):
  return self.numB

 def setNumA(self, v):
  self.numA = v

 def setNumA(self, v):
  self.numB = v

 def toString(self):
  return "A:",self.numA,"B:",self.numB

_singleton = None

def get_instance(cls = MyClass):
 global _singleton
 if _singleton is None:
  _singleton = cls()
 return _singleton

if __name__=='__main__':
 print "Main output"

 a = get_instance()
 print a.toString()
 a.setNumA(15)
 print a.toString()

 b = get_instance()
 print b.toString()

Output:
Main output
('A:', 5, 'B:', 10)
('A:', 5, 'B:', 15)
('A:', 5, 'B:', 15)

Friday, September 7, 2012

Python Markdown module



Python markdown is intended to be a python library module used by various projects to convert Markdown syntax into HTML.
Markdownld install pip command (pip install markdown)


 
import markdown

md = markdown.Markdown(safe_mode=True)
html = md.convert(content) #'html' is converted html data



Here very nice documentation of markdown. You may read it.

Python jsonpickle: object serialization and deserialization



jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON.Its support complex python object.
You need install jsonpickle first (pip command pip install jsonpickle)
Lets see a example:


 
import jsonpickle


class Subclass(object):
    subclass_value=10
    def my_fun(self):
        print "this is myfun from Subclass"

class MainClass(object):
    mainclass_data='This is main class data'
    mainclass_value=5
    sc=Subclass()


obj=MainClass()
pickle=jsonpickle.encode(obj,max_depth=1) #Here I set max_depth, so it will not recurse 
unpickleObject=jsonpickle.decode(pickle)  #deeper than 'max_depth' steps into the object 


unpickleObject.sc.my_fun()
print unpickleObject.mainclass_data



max_depth is very important, it's define maximum depth level of recursion. If you have no idea about depth level of recursion just set a mixmum value (max_depth=50000).

Output:
this is myfun from Subclass
This is main class data

Install pip on windows

Pip is very usefull for installing python packages. Lets see the installing procedure of pip on windows


  • Make sure that your python path is added to environment variable
  • download easy installer for windows & install it by clicking on the exe file or download run ez_setup.py from here
  • dowaload pip pip & uncompress it.
  • cd to the uncompress directoy and run command python setup.py install

Now you have pip. Go to the command prompt and run pip help and you will find pip command details. For example I want to install jsonpickle using pip now comand is pip install jsonpickle

Tuesday, September 4, 2012

python subclass list(reflection)



Sometimes we need get list of subclass of a class. It is very simple in python.


 
class MyClass(object): pass

class SubClassA(MyClass): pass
class SubClassB(MyClass): pass
class SubClassC(MyClass): pass

print([cls.__name__ for cls in vars()['MyClass'].__subclasses__()])




Output:
['SubClassA', 'SubClassB', 'SubClassC']


Python object serializing and de-serializing(pickle) example



Another object serialization example code.


 
import pickle

class Student(object):
    marks=None
    def __init__(self,n='name'):
        self.name=n
    def setMark(self,m=0):
        self.marks=m
    def getMark(self):
        return self.marks
    def getName(self):
        return self.name

sa=Student("AJZ")
sa.setMark(10)
pickleData=pickle.dumps(sa) #object serializing 

sb=pickle.loads(pickleData) #object de-serializing
print sb.getName()
print sb.getMark()




Output:
AJZ
10

Python object serialization, pickle



Python pickle supports serializing and de-serializing object. Let's a simple example code


 
import pickle

def pickleWrite(fileName,data):
    f = open(fileName, 'wb')
    pickle.dump(data, f)
    f.close()

def pickleRead(fileName):
    f = open(fileName, 'rb')
    data = pickle.load(f)
    f.close()
    return data

class Student(object):
    marks=None
    def __init__(self,n='name'):
        self.name=n
    def setMark(self,m=0):
        self.marks=m
    def getMark(self):
        return self.marks
    def getName(self):
        return self.name

fiieName='data.pk'

s1=Student("jonycse")
s1.setMark(5)
pickleWrite(fiieName,s1) #object s1 saved on file 'data.pk'




Now pickle object s1 saved on file 'data.pk'. You just need to read the file for getting saved object.
I am using two function named pickleWrite and pickleRead for read write data.

 


#s1=Student("jonycse")
#s1.setMark(5)
#pickleWrite(fiieName,s1)

s2=pickleRead('data.pk')
print s2.getName()
print s2.getMark()



Output:
jonycse
5

Monday, September 3, 2012

Python multiple inheritance, MRO



Python support multiple inheritance. For multiple inheritance we need to know MRO(Method Resolution Order) .I recommend to read this very interesting paper for how MRO works. Python has builtin method class.mro() method


 
class Arithmetic(object):
    def add_num(self,a,b):
        print a+b

class String(object):
    def add_num(self,a,b):
        print a-b

    def print_string_upper(self,data):
        print data.upper()

class Common(Arithmetic,String):
    def print_class_c(self):
        print "This is C"



print Common.mro()

mih=Common()
mih.add_num(2,3) #Following MRO 
mih.print_string_upper("python")
mih.print_class_c() 




Output:
[<class '__main__.Common'>, <class '__main__.Arithmetic'>, <class '__main__.String'>, <type 'object'>]
5
PYTHON
This is C

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