Python Classes and Objects with Examples

Python Classes and Objects with Examples

23 May 2024
Intermediate
107 Views
12 min read

What are Classes and Objects in Python?

Have you been learning Python? If yes, then you might have come across classes and objects many times. Python classes and objects are the starting point in Python Programming. A class in Python is a blueprint for an object and the object in Python is an instance of it but with real values. They make the code more organized and structured.

In this Python Tutorial, we’re going to dive into Python classes and objects, Python class methods, and much more. To learn more about different concepts of Python Programming, consider enrolling in our Python Certification Training.

Read More: Top 50 Python Interview Questions and Answers

Python Classes

As said before as well, a class is a blueprint that is used for creating objects. A Python class defines a structure that can be used to create multiple objects. These objects will share the same structure and behavior as defined in the class. 

Python classes

Syntax for Defining a Python Class

The syntax of a Python Class includes the Python keyword 'class', class name, and class body.
class ClassName:
    # Class body

Example for Defining a Simple Class

Let's try to understand how to define a class with the below example:
class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        print(f"{self.name} says woof!")

Here, 

  • The class keyword defines the class named 'Dog'. 
  • The __init__ method is very much like what constructors do in C++ and Java. They initialize the state of the object.
  • The self-parameter is used to reference the current instance of the class and access its variables.

Python Objects

Now, that we understand what classes are, it's time to get to know about Python objects. Objects are instances of a class. In simple words, when we create an object, an instance of the class is created that is complete with attributes and methods.

Python Objects

Creating Objects For the Class

Now we can create objects for the class we created earlier and use their methods as shown below:
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

Accessing Class Attributes Using Objects

You can access the attributes of an object like this:
print(dog1.name)
print(dog2.age)

Let's see how this program will work as a whole in a Python online Compiler.

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

    def bark(self):
        print(f"{self.name} says woof!")

# Creating objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)

# Accessing attributes
print(dog1.name)
print(dog2.age)

# Modifying attributes
dog1.age = 4
print(dog1.age)

# Calling methods
dog1.bark()
dog2.bark()

Output

Buddy
5
4
Buddy says woof!
Max says woof! 
Read More: Python Developer Roadmap: How to become a Python Developer?

Creating Multiple Objects of Python Class

We can create multiple objects in a Python class easily. Below is an example you can try in Python Editor:
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_info(self):
        print(f"{self.year} {self.make} {self.model}")

# Creating multiple objects of the Car class
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Accord", 2018)
car3 = Car("Ford", "Mustang", 2021)

# Creating a list of Car objects
cars = [car1, car2, car3]

# Iterating over the list to access each Car object
for car in cars:
    car.display_info()

In this example, 

  • We have a 'Car' class with a constructor that will initialize the 'make', 'model', and 'year' attributes. 
  • The 'display_info' method will print the car details as the output. 
  • Then, we created 3 'Car' objects that have different attribute values.

Output

2020 Toyota Camry
2018 Honda Accord
2021 Ford Mustang

Python Methods

Methods are functions in Python that are defined inside a class and are used to perform operations on objects of that class. There are several types of methods in Python:

1. Instance Methods

Instance methods are the most common type of methods in Python classes. They are used to perform actions that use or modify the data attributes of an object. They must take 'self' as their first parameter, which is a reference to the instance of the class.

Example of Instance Methods

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

    def bark(self):
        print(f"{self.name} says woof!")

    def get_age(self):
        return self.age

    def set_age(self, age):
        self.age = age

# Creating an object
dog1 = Dog("Buddy", 3)

# Calling instance methods
dog1.bark()
print(dog1.get_age())

# Modifying an attribute using a method
dog1.set_age(4)
print(dog1.get_age())

Output

Buddy says woof!
3
4

2. Class Methods

Class methods are methods that operate on the class itself and take 'cls' as their first parameter, which is a reference to the class, and are defined using the '@classmethod'.

Example of Class Methods

class Dog:
    species = "Canis familiaris"

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

    @classmethod
    def get_species(cls):
        return cls.species

# Calling class method
print(Dog.get_species())

Output

Canis familiaris

3. Static Methods

Static methods do not operate on an instance or the class itself. They do not take 'self' or 'cls' as their first parameter, but are defined using the '@staticmethod' decorator and can be called on the class itself.

Example of Static Method

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

    @staticmethod
    def is_puppy(age):
        return age < 1

# Calling static method
print(Dog.is_puppy(0.5))
print(Dog.is_puppy(2))

Output

True
False
Conclusion
This article explained to you what classes and objects in Python are and what their purpose is. I hope you will be able to use them correctly in your Python Program now. If you want to go through other concepts and terminologies of Python, enroll in our Python Certification Course right now!

FAQs

Q1. What is a Python class?

A Python class is like a blueprint for creating objects. It contains the initial values of attributes and their behaviors.

Q2. What are the classes and objects in Python?

In Python, classes are a blueprint for creating objects, while, objects are instances of the classes.

Q3. What is the difference between object and class method in Python?

The difference between an object and a class method in Python is that a class method can only access the class and not the object. Whereas, an object method can access both object and class variables.

Q4. What is a class and object?

A class defines the properties and behaviors of objects. Whereas, an object is an instance of class.
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification Course Jun 22 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core (Project) Jun 23 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Azure Developer Certification Training Jun 23 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
.NET Microservices Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jun 23 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Full Stack .Net Developer Jun 30 SAT, SUN
Filling Fast
11:00AM to 01:00PM (IST)
Get Details
ASP.NET Core Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Generative AI For Software Developers Jul 14 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this