Object Oriented Code in Python

Object Oriented Code in Python

This is time to go through the code to demonstrate the concept of OOP in Python. This is well known fact that OOP can not be done without Class and Object. So here is the example of Class and Object in Python.

Code of OOP in Python

Output of above code is –

Output of two Students Object

Now lets start understanding the code line by line. First line to Fourth line nothing but class level comment. Make it as clear and understandable as you can. Line no 8 is the beaning of class structure [class student(object): ]. It says that we are going start a class named Student and (object) is saying that this is new style of writing class and at last : is for starting the block statement. This is similar to { } sign in Java or C++

Next is [def __init__(self, name, marks):]. Here init is a function to initialise the object of class. If you are adding it well and good, if you left it don’t worry Python will insert it with default argument self on behalf of you. But here I used two extra parameters (name and marks), that means when ever user will try to create the object of Student class he/she have to pass these two parameters. After that self.name and self.marks are two instance variables which are getting initialised by parameters of init method. Remember the style of writing init method, it starts with two underscore sing and ends with the same two underscore sign.

Now you can write N numbers of methods a per your business requirement. Remember that if the function takes self as parameter are instance method and will get called by the object directly. [def getStudent(self):] this is the only function we are heving right now.

Lastly we need to create object and call method associated with that. [s1 = student(‘Robin’, 98)] will create one object s1 of student class. As my init method takes two parameters except self. So need to pass. and lastly call getStudent() on s1. You will get output as above. I created two Objects, you can create as much as you want.

That’s it. You are done with basic example of Class and Object in Python. Comments and feedback are always welcome. Bye bye…