13
SepPython Classes and Objects with Examples
What are Classes and Objects in Python?
Classes and objects are fundamental principles in object-oriented programming (OOP), allowing you to encapsulate data and behavior into a single entity. 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. Python is the #1 skill for tech’s future. Don’t lag behind. Join our Free Python Course and code your way to success!
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.
- Classes are created using the class keyword.
- Attributes are variables defined inside the class and represent the properties of the class.
- Methods are functions that define the behaviour of the class.
- Attributes can be accessed using the dot . operator (e.g., MyClass.my_attribute).
Syntax for Defining a Python Class
class ClassName:
# Class body
Example for Defining a Simple Class
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-parameteris 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.
Creating Objects For the Class
dog1 = Dog("Buddy", 3)
dog2 = Dog("Max", 5)
Accessing Class Attributes Using Objects
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
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
Constructor in Python
Class Creation Using __init__ Function
class Animal:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
def speak(self):
print(f"{self.name} sound")
def eat(self):
print(f"{self.name} is eating")
NOTE: self is always the first keyword in an instance method in a class in Python, and it represents the object on which the method is being called.
Object Creation Using __init__ Function
cat=Animal(“Tom”,6)
print(f”{cat.name} {cat.age}”)
print(f”{dog.name} {dog.age}” )
dog.speak()
dog.eat()
cat.speak()
cat.eat()
Python Methods
1. Instance Methods
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
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
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
FAQs
Take our Python skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.