Object Oriented Programming (OOP) Concepts with Example in Python

Python is an object-oriented programming language, in this everything is associated with objects and classes. Classes, a unique programming construct, are used to implement most of the code. A Python object, in general, is a collection of data elements and methods that describe the behaviour of those elements.

Python can operate on practically any platform, including Windows, all Linux distros (including all versions of Linux), Mac OS X, Unix, and many others. It can be used to create complicated programs as well as GUI (Graphical User Interface) based apps. Web applications can be developed on a server using Python.

Python is an interpretive language because the interpreter runs the Python code line by line, making debugging simpler. Python uses indentation to indicate a block of code. Python's indentation is important, unlike other programming languages where indentation just serves to make the code easier to read.

In this blog, we will learn how to create a simple class in Python and how to instantiate that class by objects. Before learning about this, we have to explore several terms to understand the topic better. Such as

Python OOPs Concept

Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of objects. In OOP, data and behavior are bundled together into objects, which can be treated as self-contained entities that interact with other objects.

#1 Class

To construct a class in Python, use the class keyword. For example,

class ClassName:
	# class definition 

Let's consider this example,

class Lorry:
    name = ""
    gear = 0

Here,
Lorry - the name of the class.
name, gear - variables inside the class with default values " " and 0 respectively.

Let’s create a simple empty class in Python,
class Employee:

It will show a syntax error.

Output:

SyntaxError: unexpected EOF while parsing

To create an empty class in Python, we use the pass statement. This is a special statement that does nothing. We can create objects for empty classes. For instance,

# empty class

class Employee:
    pass

# driver's code

emp = Employee()
print emp

Output:

In Python, we can create attributes of an object of an empty class and we can create different attributes for the different objects as well. Look at the following example,

# empty class

class Employee:
    pass

emp1 = Employee()
emp1.name = 'Nikhil'
emp1.id = '01'
emp1.office = 'NamLabs'
emp1.phone = 1234567889

emp2 = Employee()
emp2.name = 'Abhinav'
emp2.office = 'NamLabs'
emp2.phone = 1234567889

# Printing details

print 'emp1 Details:'
print ('Name:', emp1.name)
print ('Office:', emp1.office)
print ()

print 'emp2 Details:'
print ('Name:', emp2.name)
print ('Office:', emp2.office)
print ('Phone:', emp2.phone)

# Uncommenting this print("Phone:", emp1.phone)
# will raise an AttributeError

Output:

#2 Objects

An object is referred to as an instance of a class. Instance and object are used interchangeably. The realized version of the class is called an object.

Syntax to create an object:

objectName = ClassName()

Consider the below illustration,

class Lorry:
    name = ''
    gear = 0

# create objects of class
lorry1 = Lorry()

Here, lorry1 is the object of the class.

An object includes

  1. State: It is portrayed by an object's attributes. It additionally reflects an object's properties.
  2. Behaviour: The methods of an object serve as a representation of behaviour. It also shows how one object reacts to other objects.
  3. Identity: It gives an object a special name and makes it possible for one object to communicate with another.

Let’s look at this real-time example,

#3 Attributes

The variables inside a class are known as attributes. The dot (.) operator can be used to access attributes, which are always public. To access the class attributes, we can use the objects.
For example,

# modify the name attribute
lorry1.name = "Force"

# access the gear attribute
lorry1.gear

Here, name and gear are class attributes that can be accessed by object lorry1 to change and access the value of attributes.

#4 Methods

A Python class can also have a function definition. A method in Python is a function that is defined inside a class and is called when an instance of the class is called. The def keyword allows you to specify as many methods in a class, as you like.

The initial parameter for every method must be self, which normally corresponds to the calling instance.

Let’s consider the below 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 an object of Room class
study_room = Room()

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

# access method inside class
study_room.calculate_area()

Output:

Here,

Class name: Room
Attributes: length and breadth
Method: calculate_area()

Here, we've created an object from the Room class with the name study_room. After that, we applied values to the attributes such as length and width using the object. Note that we also called the method inside the class using the object.

study_room.calculate_area()

Here, we called the method using the dot (.) notation to execute the method’s statement by object study_room.

_init_() method

The __init__() method is similar to constructors in C++ and Java. Constructors are assisted to initialize the object’s state. Similar to methods, a constructor also consists of a set of statements(i.e. instructions) that are executed at the time of Object creation.

It runs as soon as an object of a class is instantiated. This method is useful to do any initialization you want to do with your object.

To assign values to object properties or do other tasks required when creating the object, use the __init__() method. The __init__() method takes the new object as its first argument, self.

Then it sets any required instance attribute to a valid state using the arguments that the class constructor passed to it.

Consider the following example,

class Person:

    # init method or constructor
    def __init__(self, name):
        self.name = name

    # Sample Method
    def say_hi(self):
        print ('Hello, my name is', self.name)

p = Person('Nikhil')
p.say_hi()

Output:

str() method

The Python __str__() method returns the string representation of the object.

Syntax of _str_method:

object.__str__(self)

The object representation is returned as a string using the Python __str__() method. A human-readable format that can be used to show certain object information is what this method is designed to return.

The string representation of an object with the __str__() function:

class Person:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"{self.name}({self.age})"

p1 = Person('John', 36)
print p1

Output

Class variables and Instance variables

Class variables are variables whose value is assigned in the class, but instance variables are variables whose value is assigned inside a constructor or method with self.

Class variables are used for attributes and methods that are shared by all instances of the class, whereas instance variables are used for data that is specific to each instance.

For example,

class Dog:

    # Class Variable
    animal = 'dog'

    # The init method or constructor
    def __init__(self, breed):

        # Instance Variable

        self.breed = breed

    # Adds an instance variable
    def setColor(self, color):
        self.color = color

    # Retrieves instance variable
    def getColor(self):
        return self.color

# Driver Code
Rodger = Dog('pug')
Rodger.setColor('brown')
print Rodger.getColor()

Output:

Create and Instantiate Class in Python

As we said earlier in this blog, a class is a blueprint of an object which is created using the class keyword and an object is an instance of a class. Object declaration is known as object instantiation.

We have already explored what are objects, attributes, methods, class variables, instance variables, and so on. Now we will see how to create and instantiate a simple class in python using these components.

A new class produces a new type of object, enabling the creation of new instances of that type. Each instance of a class may have attributes connected to it to preserve its state. Class instances may also contain methods for changing their state that is defined by their class.

Let’s consider the following example:

Let's imagine you wanted to keep tabs on the number of dogs with various attributes, such as breed and age. If a list is utilised, the dog's breed and age might be the first and second elements, respectively.

What if there were 100 different breeds of dogs? How would you know which element should go where? What if you wanted to give these dogs additional traits? This is disorganised and just what classes need.

The class produces a user-defined data structure that contains its data members and member functions and that can be accessed and used by making an instance(object) of the class.

Creating a class

In the aforementioned example, the class keyword denotes the creation of a class, followed by the class name (Dog in this case).

class Dog:
    pass

An instance is a clone of the class with actual values, whereas a class is essentially a blueprint. It is now a real dog, say a seven-year-old pug, and is no longer just an idea.

Although you can have numerous dogs to generate a variety of instances, you would be lost without the guidance of the class, if you didn't know what information was needed.

Object Declaration (Also called instantiating a class)

A class is said to be instantiated when an object belonging to a class is created. The attributes and behaviours of a class are shared by all instances.

However, the states of those attributes, or their values, are particular to each object. Any number of instances may exist for a single class.

class Dog:
    
    attr1 = 'mammal'
    attr2 = 'dog'

    # A sample method
    def fun(self):
        print ("I'm a", self.attr1)
        print ("I'm a", self.attr2)

# Driver code
# Object instantiation
Rodger = Dog()

# Accessing class attributes
# and method through objects
print Rodger.attr1
Rodger.fun()

Output:

An object (Rodger) the dog is built in the example above. In this class, Rodger is identified as a dog and a mammal by just two class attributes.

Class creation and instantiation using class and instance variables

class Dog:

    # Class Variable
    animal = 'dog'

    # The init method or constructor
    def __init__(self, breed, color):

        # Instance Variable

        self.breed = breed
        self.color = color


# Objects of Dog class
Rodger = Dog('Pug', 'brown')
Buzo = Dog('Bulldog', 'black')

print 'Rodger details:'
print ('Rodger is a', Rodger.animal)
print ('Breed: ', Rodger.breed)
print ('Color: ', Rodger.color)

print '\nBuzo details:'
print ('Buzo is a', Buzo.animal)
print ('Breed: ', Buzo.breed)
print ('Color: ', Buzo.color)

# Class variables can be accessed using class
# name also
print '\nAccessing class variable using class name'
print Dog.animal

Output:

Delete the object in a class

We can remove the properties of the object or object itself by using the del keyword.

For instance,

class Employee:

    id = 10
    name = 'John'

    def display(self):
        print 'ID: %d \nName: %s' % (self.id, self.name)

# Creating an emp instance of Employee class
emp = Employee()

# Deleting the property of the object
del emp.id

# Deleting the object itself
del emp
emp.display() 

Since we deleted the object emp, it will encounter the Attribute Error.

Conclusion

In this blog, we have gone through creating classes, instantiating objects, initializing attributes with the constructor method, and instantiating more than one object in the same class.

Now that you have this knowledge to develop your class constructors and have complete control over instance generation and initialization in your Python object-oriented programming projects.

Understanding object-oriented programming is crucial because it makes it possible to reuse code by allowing objects created for one program to be used in another.

Since complicated systems are challenging to build and need careful planning, object-oriented programming also results in better program design, which reduces the amount of effort required to maintain the program over time.


ReplayBird - Driving Revenue and Growth through Actionable Product Insights

ReplayBird is a digital experience analytics platform that offers a comprehensive real-time insights which goes beyond the limitations of traditional web analytics with features such as product analytics, session replay, error analysis, funnel, and path analysis.

With Replaybird, you can capture a complete picture of user behavior, understand their pain points, and improve the overall end-user experience. Session replay feature allows you to watch user sessions in real-time, so you can understand their actions, identify issues and quickly take corrective actions. Error analysis feature helps you identify and resolve javascript errors as they occur, minimizing the negative impact on user experience.

ReplayBird Dashboard

With product analytics feature, you can get deeper insights into how users are interacting with your product and identify opportunities to improve. Drive understanding, action, and trust, leading to improved customer experiences and driving business revenue growth.

Try ReplayBird 14-days free trial

Further Readings:

The top 5 programming languages of all time
In this blog post, we’ll be discussing the top five programming languages of all time and why they’re worth your consideration if you’re looking to develop a website, app, or piece of software.
Importance of Learning CSS in 2023
In this blog post, we will be exploring the importance of learning CSS and discussing why it’s a necessary skill for any web developer.
Correlation vs Causation - Understand Correlation in Statistics
Explore correlation in statistics and understand the difference between correlation and causation to evaluate the strength of a correlation.