Classes and Objects in Python Guide With Examples

Prashant Sharma 30 Jan, 2024 • 7 min read

Introduction

Object-Oriented Programming (OOP) is a paradigm employing classes and objects to build functional programs. Emphasizing code modularity, classes and objects craft reusable, compact code segments, forming the basis for comprehensive software features and modules. Leading OOP languages include C++, Java, and Python, excelling in today’s domains like Data Science and Statistical Analysis.

In Data Science, Python is a frontrunner due to its robust capabilities. Mastery of classes and objects is vital for aspirants venturing into Data Science, facilitating Python proficiency. Unlock insights into Python’s classes and objects with this article. Discover their intricacies and grasp the process of crafting and utilizing your unique classes. Your journey to OOP excellence begins here.

This article was published as a part of the Data Science Blogathon.

What is a Python Class?

In Python, users define a class as a prototype for creating objects, serving as a means to group data and functionality. The significance of the two keywords is crucial. Variables instantiated or defined are termed data, and operations performed on that data are termed functionality. Creating classes involves bundling data and functionality into a single package.

Example

Consider the following simple example to understand the importance of creating a class. Assume you want to keep track of dogs in your neighborhood that have different characteristics such as age, breed, color, weight, and so on. You can use a list to track elements in a 1:1 relationship, for example, tracking the breed to the age or the age to the weight. What if there are supposed to be a hundred different kinds of cats? What if more properties need to be added? Using lists in this situation is unorganized and messy.

That is where classes come into play!

Classes assist you in developing a user-defined data structure with its own data members (variables) and member functions. You can access these variables and methods by simply creating an object for the class (we’ll go over this in more detail later). In that sense, classes are similar to a blueprint for an object.

Furthermore, creating classes creates a new type of object – allowing you to create more objects of the same type. In order to maintain its state, each class instance can have attributes attached to it. Class instances can have methods for modifying the state (as defined by their class).

Some Points on Python Class

  • Using the keyword class, classes are created.
  • Attributes are the variables that are specific to the class you created.
  • These attributes are always public and can be accessed by inserting a dot after the class name. For instance, “ClassName. AttributeName” will return the specific attribute detail for that class.

Syntax for Python Class

class ClassName:
    # Statement-1
    .
    .
    .
	.
    # Statement-N

Example:

# Python3 program to
# demonstrate defining
# a class
class Dog:
      	pass

In the previous example, the class keyword indicates that you are creating a class, followed by the class name (Dog in this case).

Power up your career with the best and most popular data science language, Python. Enroll for our FREE course today!

Advantages of using Classes in Python

  • Classes help you in keeping all of the various types of data properly organised in one place. You are keeping the code clean and modular in this manner, which improves the readability of your code.
  • Using classes enables you to take advantage of another OOP paradigm known as inheritance. This occurs when one class inherits the properties of another.
  • They give you the ability to override any standard operators.
  • Classes make your code reusable, which improves the efficiency of your programme.

What are Python Objects?

An object is simply a subclass of any class you’ve defined. When you create a class, an automatic instance is created. As shown in the example, the dog class automatically creates an object that looks like a real dog – a German Shepherd dog that is three years old. There can be many different instances of dogs having different properties, but for it to make sense, you’ll need a class to guide you. Otherwise, you’ll be puzzled, unsure of what information is required.

Features of a Python Object

  • State: This refers to the different attributes and properties of every object.
  • Behaviour: This essentially indicates the object’s methods. It also reflects the interaction or response to other objects by this particular object.
  • Identity: Identity is the unique name of the object to be invoked as needed.

Declaring Objects

Declaring Objects is also called the instantiation of a class, as a default item is created in itself when you define a class (as we have previously seen) – which is the class instance. Similarly, you are creating a new instance for your class every time you create an object.

In terms of the three things we mentioned earlier (state, behavior, identity), all cases (objects) share different responses and conditions, however. Any number of objects can be in one class, as the programmer requires.

Example:

As you can see, we first created a class called the dog and then instantiated an object with the name ‘bruno.’ The three outputs we got were as follows:

  • Canidae – this was the result of the statement print(Bruno.attr1). Since Bruno is an object of the dog class and attr1 has been set as Canidae, this function returns the output Canidae.
  • I’m a Canidae – Bruno. fun(); uses the object called Bruno to invoke a function in the dog class, known as ‘fun’. The Bruno object brings with it the attributes to the function, and therefore the function outputs the following two sentences – “I’m a Canidae”.
  • I’m a dog – same reason as stated above.

Let’s now look at some important methods, as you understand how classes and objects work in Python.

The Self Method

An additional first parameter in the function definition shall be required for all methods defined in any class. No value is assigned by the programmer to this parameter. But Python gives it a value when the method is called.

As a result, it still has a technical argument if you define a function without arguments. In Python, that is called “self.” You can review your C++ concept or reference it in Java in order to better understand this. The self-method works basically in the same way.

To understand this better let’s take an example

myObject.myMethod(arg1, arg2), Python automatically transform it into myClass.myMethod(myObject, arg1, arg2).

As you can see, the object itself becomes the method’s first argument. That’s what Python’s self is all about.

The __init__ method

This procedure is similar to Java or C++ builders. The init method is used, as the builders, to initialize the state of an object. This includes a collection of instructions (statements) executed during the creation of the object. When an object for a class is instantiated, the init method automatically executes the methods you initialize.

Here is a code piece for better understanding:

# A Sample class with init method
    	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(“Yash”)
    	p.say_hi()
Output:
Hello, my name is Yash

Class and Instance Variables

Each instance has unique instance variables, whereas class variables are shared among all class instances. Instance variables receive values inside a constructor or a method with ‘self,’ while class variables have values specified within a class.

Go through the following code for a better understanding

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
Bruno = dog(“Siberian Husky”, “black and white”)
Oscar = dog(“German Shepherd”, “black and tan”)
print(“Bruno details:’) 
print(‘Bruno is a’, Bruno.animal)
print(‘Breed: ‘,Bruno.breed)
print(‘Color: ‘,Bruno.color)
print(‘nOscar details:’)
print(“Oscar is a’, Oscar.animal)
print(‘Breed: ‘,Oscar.breed)
print(‘Color: ‘,Oscar.color)
Output: 
Bruno details:
Bruno is a dog
Breed:  Siberian Husky
Color:  black and white
Oscar details:
Oscar is a dog
Breed:  German Shepherd
Color:  black and tan

Providing Behavior With Methods

In Python, methods are essential for defining the behavior of objects created from classes. Methods encapsulate functionality, allowing objects to perform actions and interact with attributes. Let’s explore various types of methods that enrich the behavior of objects.

Instance Methods With self

Instance methods are the most common type of method in Python classes. They operate on individual objects and have access to the object’s attributes via the self parameter. This parameter refers to the instance calling the method, allowing the method to manipulate the object’s state.

Code:

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def calculate_area(self):
        return 3.14 * self.radius ** 2

circle1 = Circle(5)
area = circle1.calculate_area()
print("Area of the circle:", area)

Output:

Area of the circle: 78.5

Special Methods and Protocols

Special methods, also known as “magic” methods or dunder methods (double underscores), enable customizing the behavior of built-in Python operations. These methods follow specific naming conventions like __init__, __str__, and __add__.

Code:

class ComplexNumber:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag
    
    def __add__(self, other):
        new_real = self.real + other.real
        new_imag = self.imag + other.imag
        return ComplexNumber(new_real, new_imag)

num1 = ComplexNumber(3, 5)
num2 = ComplexNumber(2, 7)
sum_num = num1 + num2
print("Sum:", sum_num.real, "+", sum_num.imag, "i")

Output:

Sum: 5 + 12 i

Class Methods With @classmethod

Class methods are defined using the @classmethod decorator and operate on the class itself rather than instances. They create alternative constructors or performing operations involving class-level attributes.

Code:

class Student:
    total_students = 0
    
    def __init__(self, name):
        self.name = name
        Student.total_students += 1
    
    @classmethod
    def get_total_students(cls):
        return cls.total_students

student1 = Student("Alice")
student2 = Student("Bob")
total = Student.get_total_students()
print("Total students:", total)

Output:

Total students: 2

Static Methods With @staticmethod

Static methods are defined using the @staticmethod decorator. They don’t have access to instance or class attributes and behave like regular functions within the class’s namespace.

Code:

class MathOperations:
    @staticmethod
    def multiply(a, b):
        return a * b

result = MathOperations.multiply(5, 3)
print("Multiplication result:", result)

Output:

Multiplication result: 15

Getter and Setter Methods vs Properties

Getter and setter methods control access to attributes and allow validation or modification before setting values. Alternatively, Python supports properties, which provide a more elegant way to get, set, and delete attributes.

Code:

class Temperature:
    def __init__(self, celsius):
        self._celsius = celsius

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Temperature cannot be below absolute zero.")
        self._celsius = value

temp = Temperature(25)
print("Initial temperature:", temp.celsius)
temp.celsius = 30
print("Updated temperature:", temp.celsius)

Output:

Initial temperature: 25
Updated temperature: 30

Conclusion

Python is a relatively easy programming language, especially for beginners. Once you have mastered the basics of it, you’ll be able to work with various Python libraries and solve data-specific problems. However, keep in mind that while understanding classes and objects is the first step, you must also learn how to work with various objects, classes, and their nuances.

Frequently Asked Questions

Q1. What is the class in Python? 

A. In Python, a class is a blueprint for creating objects with attributes (variables) and methods (functions) that define their behavior and properties.

Q2. What is the first class in Python? 

A. The “object” class is the base class for all other classes in Python. Every class implicitly or explicitly inherits from this class.

Q3. How hard is Python class? 

A. The difficulty of a Python class depends on the curriculum, your background, and your learning approach. Beginners might find initial concepts easy, but complexity can increase with advanced topics.

Prashant Sharma 30 Jan 2024

Currently, I Am pursuing my Bachelors of Technology( B.Tech) from Vellore Institute of Technology. I am very enthusiastic about programming and its real applications including software development, machine learning and data science.

Frequently Asked Questions

Lorem ipsum dolor sit amet, consectetur adipiscing elit,

Responses From Readers

Clear

Python
Become a full stack data scientist