OOPS in Python Tutorial with 3 Basic Examples ( Inheritance)

Python Code

OOPS in Python allows a programmer to create an object that contains attributes and methods. You can think OOPs as it allows to create a repeatable code that is repeatable and well organized.

When to use OOPs in Python?

Suppose you have repeated tasks and objects that are more reusable. Then you will create a class for it to use it again and again. The syntax for the class is given below.

Define the class name.

class NameOfClass():

Create a method inside the class for creating an instance of the object.

class NameOfClass():
    def __init__(self,param1,param2):
        self.param1 =param1
        self.param2=param2

Call any other functions.

def nameOfMethod(self):
        #perform some task
        print(self.param1)

Full Code of the above class syntax

class NameOfClass(): 
    def __init__(self,param1,param2):
        self.param1 =param1
        self.param2=param2

    def nameOfMethod(self):
        #perform some task
        print(self.param1)

Full explanation

You have to first define the class name. Then inside the class, you have to initialize the method that allows the python interpreter to create the instance of the object.  It has three parameters self (keyword), param1, and param2 (attributes). It allows you to create an instance of the class and initialize the class when you create its instance. Self-keyword tells the python that its a part of the class. You can also define the other methods inside the class using any name of the method to perform a task.

OOPS in Python Examples

Example 1  – Create a class Student and print out the name and age of the student.

Create a class.

class Student():
    def __init__(self,name,age):
        self.name = name
        self.age=age
    def printMethod(self):
        #perform some task
        print("Name:-"+self.name)
        print("Age:-" + self.age)

Create an instance of the class.

std = Student(name="John",age="26")

Call the function of the class.

std.nameOfMethod()

Full Code

class Student():
    def __init__(self,name,age): # Attributes are arguments or parameters Name and age
        self.name = name
        self.age=age

    def PrintMethod(self):
        #perform some task
        print("Name:-"+self.name)
        print("Age:-" + self.age)

std = Student(name="John",age="26")
std.PrintMethod()

Output

Name:-John
Age:-26

Full explanation

First of all, you have to create a class Student. Inside the initialization method, there are three parameters self, name, and age.  Name and age are attributes of the class. Then there is PrintMethod(self) method for printing the Name and Age of the Student. After creation of the class, you have to create an instance of the class. The statement std = Student(name=”John”,age=”26″) will create an instance of the class. It allows the python to initialize the values. The initialize method will assign the values of the parameter. At last, you have to call the method the class PrintMethod() for displaying the name and age of the student.

Example 2  – Calculate the perimeter and area of a rectangle.

Create a rectangle class.

class Rectangle():

Initialization Function for the instance of the class.

#inialize the class
    def __init__(self,length=1,breadth=1):
        self.length = length
        self.breadth=breadth

Create a perimeter method.

    #return perimeter
    def perimeterRectangle(self):
        return 2*(self.length +self.breadth)

Method for the Area calculation.

    #return rectangle
    def areaRectangle(self):
        return (self.length*self.breadth)

Method for printing the perimeter and area of the rectangle.

       #print the perimeter and the area
    def PrintMethod(self):
        #perform some task
        print("Perimeter:-"+ str(self.perimeterRectangle()))
        print("Area:-" + str(self.areaRectangle()))

Create a rectangle object.

obj = Rectangle(10,30)

Call all classes functions.

obj.perimeterRectangle()
obj.areaRectangle()
obj.PrintMethod()

Full Code of the above example.

class Rectangle():
    #inialize the class
    def __init__(self,length=1,breadth=1):
        self.length = length
        self.breadth=breadth
        #return perimeter
    def perimeterRectangle(self):
        return 2*(self.length +self.breadth)
        #return rectangle
    def areaRectangle(self):
        return (self.length*self.breadth)

        #print the perimeter and the area
    def PrintMethod(self):
        #perform some task
        print("Perimeter:-"+ str(self.perimeterRectangle()))
        print("Area:-" + str(self.areaRectangle()))

obj = Rectangle(10,30)
obj.perimeterRectangle()
obj.areaRectangle()
obj.PrintMethod()

Output

Perimeter:-80
Area:-300

Full Explanation

First of all, you have to initialize the instance of the class Rectangle with length and breadth as a parameter. After that perimeter ( perimeterRectangle(), area ( areaRectangle() ) and print method ( PrintMethod() )for perimeter, area calculations and print its results. The statement obj = Rectangle(10,30) will create an object (obj) of the class with 20,30 as length and breadth parameter. After that, you can use the obj object to call the perimeter, area and print method functions of the class.

Example -3 Inherit the base class

Class A

class A:
    def __init__(self):
        print("Class A created")
        #methods
    def function1(self):
        print("This is method 1,Class A")

    def function2(self):
        print("This is method 2,Class B")

Create a Class B and inherit the class A

class B(A): #inherit the class A
    def __init__(self):
        A. __init__(self) #class A Instance
        print("Class B created")

Create the object of class B and call its methods and class A  methods.

objB = B()
objB.function1() #class A method
objB.function2() #class A method
objB.function3() #class B method

Full Code

class A:
    def __init__(self):
        print("Class A created")
        #methods
    def function1(self):
        print("This is method 1,class A ")

    def function2(self):
        print("This is method 2,class A ")

class B(A): #inherit the class A
    def __init__(self):
        A. __init__(self) #class A object
        print("Class B created")
    def function3(self):
        print("This is the method of class B")


objB = B()
objB.function1() #class A method
objB.function2() #class A method
objB.function3() #class B method

Output

Class A created
Class B created
This is method 1,class A 
This is method 2,class A 
This is the method of class B

Explanation

When you defined a class A and wants to inherit it in other class then you have to pass class name inside the () bracket class B(A). It allows you to use all the method and attributes inside the inherited function.

 

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Sukesh ( Chief Editor ), a passionate and skilled Python programmer with a deep fascination for data science, NumPy, and Pandas. His journey in the world of coding began as a curious explorer and has evolved into a seasoned data enthusiast.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner