• Articles
  • Tutorials
  • Interview Questions

Python Classes and Objects

Tutorial Playlist

Table of content

Show More

Python is an object-oriented language and almost every entity in Python is an object, which means that programmers extensively use classes and objects while coding in Python. Objects in Python are basically an encapsulation of Python variables and functions that they get from classes.

So, without further delay, let’s get started.

Watch this video on “Python Classes and Objects”:

Video Thumbnail

What is an Object in Python?

Python is an object-oriented programming language, with its primary emphasis being object creation and manipulation. Everything in the Python universe can be considered an object; we can check its status using type(), which just includes variables and python functions from Python itself. There are various objects such as lists, dictionaries, files, sets, strings, etc. whose types vary–just consider integer variables! An object’s class defines its properties as State Identity Behavior, which are physical entities within themselves that define how an object functions within itself and vice versa.

Concept of Python Class

A Python class can be thought of as an abstract logical entity that serves as an initial prototype or template to construct objects. Python classes offer methods for changing an object’s state as well as specifying any qualities an object might possess.

Python Class Variables

Every object instance within a class shares the same Python class variable. When creating the class itself, these variables are set up; they do not appear within any method calls on its methods.

Example of Python Classes and Objects

Let’s take an example to understand the concept of Python classes and objects. We can think of an object as a regular day-to-day object, say, a car. Now, as discussed above, we know that a class has its own data and functions defined inside of it, and all this data and functions can be considered features and actions of the object, respectively. That is, the features (data) of the car (object) are color, price, number of doors, etc. The actions (functions) of the car (object) are speed, application of brakes, etc. Multiple objects with different data and functions associated with them can be created using a class, as depicted in the following diagram.

Advantages of Using Classes in Python

  • Classes provide an easy way of keeping the data members and methods together in one place, which helps keep the program more organized.
  • Using classes also provides another functionality of this object-oriented programming paradigm, that is, inheritance.
  • Classes also help in overriding any standard operator.
  • Using classes provides the ability to reuse the code, which makes the program more efficient.
  • Grouping related functions and keeping them in one place (inside a class) provides a clear structure to the code, which increases the readability of the program.

Creating a Python Class

Just as a function in Python is defined using the ‘def’ keyword, a class in Python is also defined using the ‘class’ keyword, followed by the class name.

Much like functions, we use docstrings in classes as well. Although the use of docstrings is not mandatory, it is still recommended, as it is considered a good practice to include a brief description of the class to increase the readability and understandability of the code.

The following example illustrates how to define a class in Python:

class IntellipaatClass:
“Class statements and methods here'”

The ‘create class’ statement will create a local namespace for all the attributes, including the special attributes that start with double underscores (__), for example, __init__() and __doc__(). As soon as the class is created, a class object is also created, which is used to access the attributes in the class. Let us understand this with the help of the following Python class example:

class IntellipaatClass:
a = 5
def function1(self):
print(‘Welcome to Intellipaat’)
#accessing attributes using the class object of same name
IntellipaatClass.function(1)
print(IntellipaatClass.a)

Output:

Welcome to Intellipaat
5 

Creating an Object in Python

As we saw in the prior topic, class objects with  similar names to those of the classes are used to access attributes; they can also be used to create new objects, which can then access attributes as demonstrated in this example shown below:

class IntellipaatClass:
a = 5
def function1(self):
print(‘Welcome to Intellipaat’)#creating a new object named object1 using class object
object1 = IntellipaatClass()

Output:

Welcome to Intellipaat

At first glance, it may appear odd that we use an argument named ‘self’ while creating functions in classes but don’t actually pass any values to it when calling functions from objects. This is due to the fact that when objects call functions using methods, they pass their own object as the first argument, automatically, to their functions; thus, object1.function1() would equate directly to object1.function1(object1). Thus, the very first argument in functions should always be the object itself (typically known by its conventional name’self’ – though other names could still work – convention should always follow these practices!).

Modifying and Deleting an Object

You can modify an object like this:

Person.age=20

You can delete an object by using del keyword

For example,

del objectName

Types of Classes in Python

There are various types of classes in Python, some of which are mentioned as follows:

  • Python Abstract Class
  • Python Concrete Class
  • Python Partial Class

Python Abstract Class

An abstract class is a class that contains one or more abstract methods. The term “abstract method” refers to a method that has a declaration but no implementation. When working with a large codebase, it might be difficult to remember all the classes. That is when a Python Abstract Class can be used. Python, unlike most high-level languages, does not have an abstract class by default.

A class can be defined as an abstract class using abc. ABC, and a method can be defined as an abstract method using abc.abstractmethod. The abbreviation for abstract base class is ABC. The ABC module, which provides the foundation for building Abstract Base Cclasses, must be imported. The ABC module operates by decorating base class methods as abstract. It installs concrete classes as the abstract base’s implementations.

Example:

From abc import ABC, abstractmethod
Class AbstractClassName(ABC):
@abstract method
def abstract_method_name(self):
Pass

Python Concrete class

Concreate classes have only concrete methods, but abstract classes can have both concrete and abstract methods. The concrete class implements abstract methods, but the abstract base class can also do the same by initiating the methods through ‘super ().’

Python Partial Class

One of the Python classes, partial, can help us develop functions that only apply subsets of statements and keywords we pass to it to create new objects as a result. We can utilize the ‘Functools’ module for its implementation.

Get 100% Hike!

Master Most in Demand Skills Now!

Python File Object

The Python file object offers access to and manipulation of files through methods and properties. We can read and write to any file by using file objects.

Python produces a file object anytime we open a file to conduct any operations on it. We can use Python’s built-in functions, such as ‘open()’ and ‘os.popen,’ to generate a file object ().

When a file object is misused or a file action fails due to an I/O-related issue, the IOError exception is thrown.

A file object can be classified into three categories: text files, binary files, and raw files.

The __init__() Function in Python

In Python classes, “__init__” method is reserved. It is automatically called when you create an object using a class; it is used to initialize the variables of the class. It is equivalent to a constructor.

    • Like any other method, the init method starts with the keyword “def.”
    • “self” is the first parameter in this method, just like any other method, although in the case of init, “self” refers to a newly created object, unlike other methods where it refers to the current object or instance associated with that particular method.
    • Additional parameters can be added.

    The following example illustrates how to use the __init__() function:

class IntellipaatClass:
    def __init__(self, course):
        self.course = course
    def display(self):
        print(self.course)
object1 = IntellipaatClass("Python")
object1.display()
Output:
Python

In the above example, the init function behaves as a constructor, and it is called automatically as soon as the ‘object1 = IntellipaatClass(“Python”)’ statement is executed. Since it is a function inside a class, the first argument passed in it is the object itself, which is caught in the ‘self’ parameter. The second parameter, i.e., course, is used to catch the second argument passed through the object, that is, ‘Python’. And then, we initialized the variable course inside the init function. Further, we have defined another function named ‘display’ to print the value of the variable. This function is called using object1.

Note: Don’t forget to give proper indentation in the above code.

Python Inheritance and its Types

As a result of being an object-oriented programming language, Python also utilizes inheritance. The ability of a class to inherit the properties of another class is known as inheritance. The class that inherits the properties is usually called a subclass or derived class. The class that is being inherited is known as a superclass or a base class.

Inheritance provides code reusability, as we can use an existing class and its properties rather than creating a class from scratch with the same properties.

class derived_Class_Name (base class):

Example:

class Intellipaat:
    def course(self):
        print("Python tutorial")
class hello(Intellipaat):
    def func(self):
        print("Welcome to intellipaat")
ob1 = hello()
ob1.func()
ob1.course()

Output:

Welcome to Intellipaat
Python tutorial

There are different forms of inheritance depending on the structure of the inheritance taking place between a derived class and a base class in Python. Let’s discuss each one of them individually:

  1. Single inheritance: The type of inheritance when a class inherits only one base class is known as single inheritance, as we saw in the above example.
  2. Multiple inheritance: When a class inherits multiple base classes, it’s known as multiple inheritance. Unlike languages like Java, Python fully supports multiple inheritance. All the base classes are mentioned inside brackets as a comma-separated list.

Example:

class BaseClass1():
    def __init__(self):
        print("Base class 1")
class BaseClass2():
    def __init__(self):
        print("Base class 2")
class derivedClass (BaseClass1, BaseClass2):
    def __init__(self):
        BaseClass1.__init__(self)
        BaseClass2.__init__(self)
        print("derived class")
    def display_all(Self):
        print(self.ob1, self.ob2)
ob = derivedClass()

Output:

Base class 1
Base Class 2
derived class
  1. Multilevel Inheritance: When one class inherits a base class and then another class inherits this previously derived class to form a ‘parent, child, and grandchild’ class structure, then it’s known as multilevel inheritance. The example given below will clarify the concept:
class BaseClass():
    def __init__(self):
        print("Base class")
class childClass(BaseClass):
    def __init__(self):
        print("Child class")
class grandchildClass(childClass):
    def __init__(self):
        BaseClass.__init__(self)
        childClass.__init__(self)
        print("Grand child class")
ob1 = grandchildClass()

Output:

Base class
Child class
Grand child class
  1. Hierarchical Inheritance: When there is only one base class inherited by multiple derived classes, it is known as hierarchical inheritance..
  2. Hybrid Inheritance: Hybrid inheritance is when there is a combination of the above-mentioned inheritance types, that is, a blend of more than one type of inheritance.

Private Attributes of a Class in Python

While implementing inheritance, there are certain cases where we don’t want all the attributes of a class to be inherited by the derived class. In those cases, we can make those attributes private members of the base class. We can simply do this by adding two underscores (__) before the variable name. The example given below will clarify this concept:

Example:

class Base1:
    def __init__(self):
        self.x = 10
# creating a private variable named y
    def __init__(self):
        self.__y = 5
class Derived1(Base1):
    def __init__(self):
        self.z = 20
        Base1.__init__(self)
ob1 = Derived1()
print(ob1.y)

When the above code block is executed, it will give the following error:

Output:

Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘Derived1’ object has no attribute ‘y’

Since y is a private variable in the base class, the derived class is not able to access it.

Polymorphism in Python

Polymorphism means having many forms. Polymorphism in Python enables the use of a single interface with different Python data types, classes, or even a different number of inputs.

Polymorphism is of two types, which are mentioned below:

  • Run-Time Polymorphism
  • Compile-Time Polymorphism

Run-Time Polymorphism

Run-time polymorphism is the process by which the call to an overridden method is resolved at run time. In Python, we implement run-time polymorphism through method overriding.

Method overriding allows us to change the implementation of a method in the child class, which is defined in the parent class.

To override a method, the following conditions must be met:

  • There should be an inheritance. The child class should be derived from the parent class.
  • The method that we are redefining must have the same number of parameters as the method in the parent class.

Example:

class Animal:
def sound(self):
print("Animal sound")
class Cat(Animal):
def sound(self):
print("Cat says meow")
animal=Animal()
cat=Cat()
animal.sound()
cat.sound()

Output:

Animal sound
Cat says meow

Compile-Time Polymorphism

Compile-time polymorphism refers to a process by which calls to methods are resolved at compile time; we implement compile-time polymorphism through overloading methods.

In Python classes, method overloading allows you to implement identical functionality with various parameters. Although Python does not support compile-time polymorphism directly, there is still an effective workaround available, as shown in the following example:

Example:

class Example:
def multiply(self,a,b,c=1):
print(a*b*c)
example=Example()
example.multiply(5,10)
example.multiply(2,5,6)

Output:

50
60

Mutable and Immutable Objects in Python

A mutable object is a changeable object that can be modified after it is created. Lists, dicts, sets, and byte arrays are all mutable objects.

An immutable object is an object whose state can never be modified after it is created. Int, float, complex, Python string, tuple, frozen set, and bytes are immutable objects.

Python handles mutable and immutable objects in different ways. Mutable objects are of great use in scenarios where there is a need to change the object’s size. Immutable objects are used when you want an object that you created to always stay the same as it was when it was created.

With this, we come to the end of this module in the Python tutorial. Now, if you want to know how Python is used for data science, you can go through the blog post on Python Data Science tutorial.

Further, check out our offers for Python Certification Course and also refer to the trending Python developer interview questions prepared by the industry experts.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.