Python – OOP

With the help of examples, you’ll learn about Object-Oriented Programming (OOP) in Python and its core concepts.

Object Oriented Programming

The program is easy to understand and efficient thanks to Object-Oriented Programming.
The code can be reused because the class is sharable.
Data abstraction keeps data safe and secure.
Polymorphism allows programmers to build efficient code by allowing multiple objects to have the same interface.

An object has two characteristics:

  • attributes
  • behavior

Let’s take an example:

A parrot is an object, as it has the following properties:

  • name, age, color as attributes
  • singing, dancing as behavior

The concept of OOP in Python focuses on developing reusable code. This principle is also known as DRY (Don’t Repeat Yourself).

In Python, the concept of OOP follows some basic principles:


Class

A user-defined prototype for an object that specifies a set of attributes that all objects of the class must have. Data members (class variables and instance variables) and methods are the attributes, which are accessed using dot notation.

The example for class of parrot can be :

class Parrot:
    pass

The class keyword is used to create an empty class called Parrot. We create instances from classes. A specific object formed from a certain class is referred to as an instance.


Object

A class is instantiated as an object (instance). Only the object’s description is defined when class is defined. As a result, no memory or storage is assigned.

The example for object of parrot class can be:

obj = Parrot()

Here, obj is an object of class Parrot.

Assume we have information about parrots. Now we’ll teach you how to create the parrot class and objects.

Example 1: Creating Class and Object in Python

class Parrot:

    # class attribute
    species = "bird"

    # instance attribute
    def __init__(self, name, age):
        self.name = name
        self.age = age

# instantiate the Parrot class
blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes
print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes
print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))

Output

Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old

Methods

Methods are functions defined within a class’s body. They’re used to describe how an object behaves.

Example 2 : Creating Methods in Python

class Parrot:
    
    # instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # instance method
    def sing(self, song):
        return "{} sings {}".format(self.name, song)

    def dance(self):
        return "{} is now dancing".format(self.name)

# instantiate the object
blu = Parrot("Blu", 10)

# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())

Output

Blu sings 'Happy'
Blu is now dancing

Inheritance

Inheritance is a technique for generating a new class that uses the details of an existing one without changing it. A derived class is the freshly produced class (or child class). The existing class is also a basic class (or parent class).

Example 3: Use of Inheritance in Python

# parent class
class Bird:
    
    def __init__(self):
        print("Bird is ready")

    def whoisThis(self):
        print("Bird")

    def swim(self):
        print("Swim faster")

# child class
class Penguin(Bird):

    def __init__(self):
        # call super() function
        super().__init__()
        print("Penguin is ready")

    def whoisThis(self):
        print("Penguin")

    def run(self):
        print("Run faster")

peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()

Output

Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster

Encapsulation

One of the core principles in object-oriented programming is encapsulation (OOP). It discusses the concept of data wrapping and the methods that operate with data as a single unit. This prevents data from being accidentally modified by restricting direct access to variables and methods. An object’s variable can only be altered by an object’s method to prevent unintentional changes. These variables are referred to as private variables.

A class is an example of encapsulation as it encapsulates all the data that is member functions, variables, etc.

Example 4: Data Encapsulation in Python

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

Polymorphism

Polymorphism is the ability to use a same interface for various forms (in OOP) (data types).

Let’s say we need to color a shape; there are a variety of shapes to choose from (rectangle, square, circle). We could, however, apply the same technique to color any form. Polymorphism is the term for this notion.

Example 5: Using Polymorphism in Python

class Parrot:

    def fly(self):
        print("Parrot can fly")
    
    def swim(self):
        print("Parrot can't swim")

class Penguin:

    def fly(self):
        print("Penguin can't fly")
    
    def swim(self):
        print("Penguin can swim")

# common interface
def flying_test(bird):
    bird.fly()

#instantiate objects
blu = Parrot()
peggy = Penguin()

# passing the object
flying_test(blu)
flying_test(peggy)

Output

Parrot can fly
Penguin can't fly

Key Points to Remember:

  • The program is straightforward to understand and efficient thanks to Object-Oriented Programming.
  • The code can be reused because the class is sharable.
  • Data abstraction keeps data safe and secure.
  • Polymorphism allows programmers to build efficient code by allowing multiple objects to have the same interface.

Leave a Comment

Your email address will not be published.