Showing posts with label learn python. Show all posts
Showing posts with label learn python. Show all posts

Tuesday, July 21, 2015

Object Oriented Programming with Python

Object oriented programming is the way of looking at things in hand as object. Think Object as a real life thing with certain properties and attributes. Suppose we have a list of student,we think about students -they have a name, age, class,grade etc. as their properties or attributes and some method like finding average number, finding next grade etc. So, we generalize the concept of student as class Student and every individual student is the object of that class. Lets see the python programming examples  -

class Student:
        def __init__(self,name,age):
                self.name=name
                self.age=age
                self.grades=list()
        def __str__(self):
                return "Name :%s"%(self.name)+" "+"Age:%2d"%self.age
        def set_grades(self,grade):
                self.grades.append(grade)
        def avg_grades(self):
                return float(sum(self.grades))/len(self.grades)

Look at the example above, we have defined a class Student in the first statement. Notice the colon and indentation. Like other object oriented programming language we need to or rather we should  initialize classes with their attributes. The class Student has two attributes which need to be passed when we want to create an instance of the class. So, to create an Student object we need to write like below -

a=Student("Jhon",23)

This will create a Student object with name "Jhon" and age as 23. Next we have __str__() method, which is nothing but a show value kind of method. Write str(a) to understand what it is.
Now, we have not supplied the grades any value in the initialization phase of the class. To add grades to the Student we have created we have to write -

a.set_grades(89)

a.set_grades(78)
a.set_grades(99)
a.set_grades(79)
a.set_grades(76)

The next method avg_grades() will simply sums all the grades , then take  average and returns it.
To run it, you should write something like -
a.avg_grades()

Now look at the example below - 

class Grad_Student(Student):
        def __init__(self,name,age,university):
                Student.__init__(self,name,age)
                self.university=university
        def __str__(self):
                return "Name :%s"%(self.name)+" "+"Age:%2d"%self.age+"  "\
                       +"University:%s"%self.university

       
The class above inherited from the Student class i.e. it can access to all the methods defined in the Student class. Look at the initialization process, the __init__method here takes three argument with one extra argument 'university' and then it calls the __init__ of Student class which initialized the name and age attributes of the class and the other attribute university is initialized here.

 We can use the set_grades() and avg_grades() of the Student class from the Grad_Student class.


Also look at the __str__() here. This  is the example of polymorphism. The method described here overwites the method in Student class. So when run str(a) it will run the method here. 



Please visit my website http://pythonbeginner.in for further studies and learn python effortlessly.

Saturday, July 18, 2015

Python File I/O

Python comes with easy to use inbuilt functions for handling files. Like other programming practices files can be opened in read , write and append mode in python. There are also binary read and write mode and also r+ mode available. I will go through each of them.

To open a file , you have to write -
   f=open('filename','mode')
The default mode  in python is 'r' mode i.e. if you don't supply anything to mode option it will open the file in read mode. In read mode you can only read the file, you can not modify or erase the file content.
In write mode you can create a file. It erases a file if it has a same name. So handle it carefully, you don't want to delete important file with same name.
Append mode helps to write something in an already written file. It appends the new data in the file without deleting previous content.
In r+ mode you can open the file in both read and write mode altogether.

Let's understand a file operation by example.

This python program examples will find out share price of your favorite share and make a file consisting of all the share prices in different interval of times.

import urllib,time
f=open('mcxwholedayprice.txt','w')
s=str(time.strftime("%H:%M:%S"))
(hour,minutes,seconds)=s.split(':')
hour=int(hour)
curhour=0
while curhour<hour+12:
      
        page=urllib.urlopen("https://www.google.com/finance?q=NSE%3AMCX&ei=eIqoVcGIEsuYuATZpZ3gBw")
        text=page.read().decode("utf8")
        #print text
        text=text.lstrip()
        where=text.find("ref_272295776418103_l")
        #print where
        a="The MCX Share Price ",text[where+23:where+31]
        f.write(str(a))
        time.sleep(900)
        s=str(time.strftime("%H:%M:%S"))
        (curhour,minutes,seconds)=s.split(':')
        curhour=int(curhour)
f.close() 


Take a close look at the program above. The program imports two modules urllib and time. urllib is needed to open a website page from given url. First of all I needed to find the share price of my favorite share in google finance and write the link in the urlopen() function.Then I call time.strftime() to get the time now in a desired format and get the hour out of the format by s.split()-previously discussed in string section.
The while loop will run for 12 hours and record all the data needed to the variable a. The variable then converted to string and then written to the file we have opened in write mode. Finally it closes the file.
You can do it in your way, there are redundant line for better understanding and they can be easily removed. Can you find them out?

The other operation is read () method in python file handling. You have written a file in the previous program. To read the content of the file you need to write the following  -

f=open('mcxwholedayprice.txt','r')
print f.read()
f.close()

You can give arguments in read() function too.e.g. f.read(20) - Reads the twenty characters of the file.
f.readline() - Used to read single line of the file.
f.readlines() - Read the file line by line formatted as a list.
f.tell() - Tell the current position of file head or handler.
f.seek(n) - Goes direct to nth character of the file.



Visit my website for more free contents and more programs on files at http://pythonbeginner.in
and learn python.

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...