Mastering Python Object-Oriented Programming Essentials

Object Oriented Programming In Python

Python is a multipurpose programming language that supports various programming styles, together with object-oriented programming (OOP) through the use of objects and classes.

An object is any existence that has multiplication and behaviors. For example, a parrot is an object. It has

  • attributes - name, age, color, etc.
  • behavior - dancing, singing, etc.

Likewise, a class is a blueprint for that object.

Class and Object In Python

class Parrot:

    # class attribute
    name = ""
    age = 0

# create parrot1 object
parrot1 = Parrot()
parrot1.name = "Blu"
parrot1.age = 10

# create another object parrot2
parrot2 = Parrot()
parrot2.name = "Woo"
parrot2.age = 15

# access attributes
print(f"{parrot1.name} is {parrot1.age} years old")
print(f"{parrot2.name} is {parrot2.age} years old")

Output:

Blu is 10 years old
Woo is 15 years old

In the upon example, we maked a class with the name Parrot with two attributes: name and age.

After, we make example of the Parrot class. There, parrot1 and parrot2 are mentions (value) to our new objects.

We then appreciated and assigned several values to the instance attributes using the objects name and the . notation.

Python Inheritance In Python Programming

Inheritance is a way of making a new class for using details of an subsisting class without modifying it.

The newly formed class is a evolved class (or child class). Likewise, the existing class is a base class (or parent class).

Example 2: Use of Inheritance in Python Program

# base class
class Animal:
    
    def eat(self):
        print( "I can eat!")
    
    def sleep(self):
        print("I can sleep!")

# derived class
class Dog(Animal):
    
    def bark(self):
        print("I can bark! Woof woof!!")

# Create object of the Dog class
dog1 = Dog()

# Calling members of the base class
dog1.eat()
dog1.sleep()

# Calling member of the derived class
dog1.bark();

**Output: **

I can eat!
I can sleep!
I can bark! Woof woof!!

Below, dog1 (the object of derived class Dog) can entrance members of the base class Animal. It’s because Dog is traditional from Animal.

# Calling members of the Animal class
dog1.eat()
dog1.sleep()

Encapsulation In Python

Encapsulation is one of the key fervidity of object-oriented programming. Encapsulation refers to the bundling of multiplication and methods inside a single class.

In Python Program, we tick private attributes using underscore as the prefix i.e single _ or double __. Now for example-

class Computer:

    def __init__(self):
        self.__maxprice = 900

    def sell(self):
        print("Selling Price: {}".format(self.__maxprice))

    def setMaxPrice(self, price):
        self.__maxprice = price

c = Computer()
c.sell()

# change the price
c.__maxprice = 1000
c.sell()

# using setter function
c.setMaxPrice(1000)
c.sell()

Output:

Selling Price: 900
Selling Price: 900
Selling Price: 1000

In the upon program, we defined a Computer class.

We can used __init__() method to store the maximum selling price of Computer. Below, notice the code

c.__maxprice = 100 

Below, we have tried to temper the value of __maxprice beside of the class. Only, since __maxprice is a private variable, this interchange is not seen on the output.

As known, to change the value, we have to use a setter function i.e setMaxPrice() As takes price as a parameter.

Polymorphism In Python programming

Polymorphism is other important concept of object-oriented programming. It just, means more than one form.

So that, the same entity (method or operator or object) can perform several operations in different scenarios.

Now please see an example-

class Polygon:
    # method to render a shape
    def render(self):
        print("Rendering Polygon...")

class Square(Polygon):
    # renders Square
    def render(self):
        print("Rendering Square...")

class Circle(Polygon):
    # renders circle
    def render(self):
        print("Rendering Circle...")
    
# create an object of Square
s1 = Square()
s1.render()

# create an object of Circle
c1 = Circle()
c1.render()

Output:

Rendering Square...
Rendering Circle...

In the upon example, we have maked a superclass: Polygon and two subclasses: Square and Circle. Advertisement the use of the render() method.

The main motive of the render() method is to render the features. Still, the process of rendering a square is several from the process of rendering a circle.

There, the render() method behaves severally in different classes. Or, we can say render() is polymorphic.

Classes and Objects In Python

In the last Python tutorial, we have learned about Python OOP. We know that Python is also supports the idea of objects and classes.

An object is merely a collection of data (variables) and methods (functions). Likewise, a class is a blueprint for that object.

Python Classes In python Programming

A class is deliberated a blueprint of objects.

We can consider of the class as a sketch (prototype) of a house. It comprise all the details about the floors, doors, windows, etc.

Based on these descriptions, we construct the house; the house is the object.

Since many houses can be made from the same description, we can make many objects from a class.

Define Class In Python Programming

We can use the class keyword to create a class in Python. For example-

class ClassName:
    # class definition 

Below, we have maked a class named ClassName.

Now lets see an example

class Bike:
    name = ""
    gear = 0

Below-

  1. Bike - the name of class
  2. name/gear - variables under the class with default values "" and 0 respectively.

Python Objects In Python Programming

An object is called an precedent of a class.

If Bike is a class then we can make objects like bike1, bike2, etc from the class.

Below, the syntax to make an object.

objectName = ClassName()

Now, lets see an example-

# create class
class Bike:
    name = ""
    gear = 0

# create objects of class
bike1 = Bike()

Below, bike1 is the object of the class. Now, we can use this object to access the class qualities.

Access Class Attributes Using Objects In Python

We can use the . notation to access the qualities of a class. For example-

# modify the name property
bike1.name = "Mountain Bike"

# access the gear property
bike1.gear

Below, we have used bike1.name and bike1.gear to make change and access the value of name and gear attributes, respectively.

Example 1: Python Class and Objects In Python Program

# define a class
class Bike:
    name = ""
    gear = 0

# create object of class
bike1 = Bike()

# access attributes and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike"

print(f"Name: {bike1.name}, Gears: {bike1.gear} ")

Output:

Name: Mountain Bike, Gears: 11

In the upon example, we have defined the class named Bike with two qualities: name and gear.

And We have also created an object bike1 of the class Bike.

At last, we have accessed and modified the possession of an object using the . notation.

Create Multiple Objects of Python Class In Python program

We can also make multiple objects from a single class. For example-

# define a class
class Employee:
    # define a property
    employee_id = 0

# create two objects of the Employee class
employee1 = Employee()
employee2 = Employee()

# access property using employee1
employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")

# access properties using employee2
employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")

Output:

Employee ID: 1001
Employee ID: 1002

In the upon example, we have maked two objects employee1 and employee2 of the Employee class.

Methods In Python Programing

We can also identify a function under a Python class. A Python function identify inside a class is called a method.

Now lets see an example-

# create a class
class Room:
    length = 0.0
    breadth = 0.0
    
    # method to calculate area
    def calculate_area(self):
        print("Area of Room =", self.length * self.breadth)

# create object of Room class
study_room = Room()

# assign values to all the properties 
study_room.length = 42.5
study_room.breadth = 30.8

# access method inside class
study_room.calculate_area()

Output:

Area of Room = 1309.0

In the upon example, we have created a class named Room with:

  • Attributes: length and breadth
  • Method: calculate_area()

There, we have created an object named study_room from the Room class.

After we used the object to assign values to attributes: length and breadth.

Advertising that we have also used the object to call the method under the class,

study_room.calculate_area()

Below, we have used the . notation to call the method. At last, the statement under the method is executed.

Constructors In Python Program

Before we assigned a default value to a class attribute,

class Bike:
    name = ""
...
# create object
bike1 = Bike()

But, we can also initialize values using the constructors. For example-

class Bike:

    # constructor function    
    def __init__(self, name = ""):
        self.name = name

bike1 = Bike()

Above, __init__() is the constructor function that is called whensoever a new object of that class is instantiated.

The constructor upon start the value of the name attribute.

We have used the self.name to mention to the name attribute of the bike1 object.

Suppose we use a constructor to initialize values under a class, we need to pass the resembling value during the object creation of the class.

bike1 = Bike("Mountain Bike")

Above, "Mountain Bike" is passed to the name parameter of __init__().

Inheritance In Python

Essence an object-oriented language, Python confirmation class inheritance. It assume us to create a new class from an subsisting one.

  • The recently created class is known as the subclass (child or derived class).
  • The subsisting class from which the child class inherits is known as the superclass (parent or base class).

Python Inheritance Syntax In Python Program

# define a superclass
class super_class:
    # attributes and method definition

# inheritance
class sub_class(super_class):
    # attributes and method of super_class
    # attributes and method of sub_class

Above, we are inheriting the sub_class from the super_class.

Example: Inheritance In Python

class Animal:

    # attribute and method of the parent class
    name = ""
    
    def eat(self):
        print("I can eat")

# inherit from Animal
class Dog(Animal):

    # new method in subclass
    def display(self):
        # access name attribute of superclass using self
        print("My name is ", self.name)

# create an object of the subclass
labrador = Dog()

# access superclass attribute and method 
labrador.name = "Rohu"
labrador.eat()

# call subclass method 
labrador.display()

Output:

I can eat
My name is  Rohu
Previous
Python File Handling Essential Tips and Tricks for Mastery