Friday, April 27, 2012

Classes in Python

Class creation and instantiation is cleaner and a lot more easier in Python.
class Student:
    def __init__(self):
    def getName(self,name): = name
    def totalMarks(self,fmarks,smarks,tmarks):
        self.fmarks = fmarks
        self.smarks = smarks
        self.tmarks = tmarks
        tot_marks = fmarks+smarks+tmarks
        print tot_marks

Messi = Student()

In the above Python code snippet we  have created a class template Student.
Now let us analyze it :

  • We have a method __init__ which acts as a constructor in Python. This function is automatically called when the class in instantiated. We have used "pass" just to pass the method and do nothing.
  • We also see that all the functions in the class take the first argument as "self" ."self" is actually a placeholder used in Python set as a first argument in functions.This is replaced with the object which is used to call that function. For Example if we created an instance of student as "Messi" , then when we call a function using this object,then the self is replaced with the object "Messi".
  • getName() method takes the name of the Student and assigns it to the Object's name parameter which called this function.
  • totalMarks() method takes the marks scored by students in 3 tests and calculates the Total Marks.
  • Further Down we have a created an instance of the class Student "Messi".
  • Using the Object Messi we called the getName() and totalMarks() methods using dot(.) notation.
  • As you can observe we do not pass anything in place of self parameter of methods , as we already know that it is just a place holder.

That's it , Class creation is that's simple and fun.

No comments: