22
DecPython Classes and Objects with Examples
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.
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-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.
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
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