Python Classes and Objects
In Python, classes and objects are the foundation of object-oriented programming (OOP). A class is a blueprint for creating objects, while an object is an instance of a class with its own data and behavior.
Defining a Class in Python
A class is defined using the class
keyword. Inside the class, we can define attributes (variables) and methods (functions).
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def method_name(self):
return f"Attribute1: {self.attribute1}, Attribute2: {self.attribute2}"
Creating an Object
Once a class is defined, we can create an object (also called an instance) of that class.
obj = ClassName("Value1", "Value2")
Example 1: Creating a Simple Class and Object
In this example, we create a class called Person
with two attributes: name
and age
. We also define a method introduce()
that prints a simple introduction.
We then create an object (instance) of the Person
class and call the method to see the output.
class Person:
def __init__(self, name, age):
# Assigning attributes
self.name = name
self.age = age
def introduce(self):
# Printing an introduction using the object's attributes
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Creating an instance of the Person class
person1 = Person("Arjun", 25)
# Calling the method
person1.introduce()
Output:
Hello, my name is Arjun and I am 25 years old.
Here, the __init__()
method initializes the attributes when we create the object person1
. The method introduce()
is then called on the object to display the introduction message.
Example 2: Class with Multiple Methods
In this example, we define a class Car
that represents a car with attributes brand
and speed
. The class has multiple methods:
display_info()
: Displays the car’s brand and speed.accelerate()
: Increases the speed of the car.brake()
: Reduces the speed of the car.
class Car:
def __init__(self, brand, speed):
self.brand = brand
self.speed = speed
def display_info(self):
print(f"Car brand: {self.brand}, Speed: {self.speed} km/h")
def accelerate(self, increase):
self.speed += increase
print(f"The car accelerates. New speed: {self.speed} km/h")
def brake(self, decrease):
self.speed -= decrease
print(f"The car slows down. New speed: {self.speed} km/h")
# Creating an object of the Car class
car1 = Car("Tesla", 100)
# Displaying initial car details
car1.display_info()
# Accelerating the car
car1.accelerate(20)
# Applying brakes
car1.brake(30)
Output:
Car brand: Tesla, Speed: 100 km/h
The car accelerates. New speed: 120 km/h
The car slows down. New speed: 90 km/h
Here, the car’s speed changes dynamically using the accelerate()
and brake()
methods.
Example 3: Handling Errors in Class Usage
Sometimes, users might provide incorrect input types. We can use error handling inside class methods to prevent such issues. In this example, we ensure the speed value is always a valid number.
class SafeCar:
def __init__(self, brand, speed):
self.brand = brand
self.set_speed(speed)
def set_speed(self, speed):
# Ensuring speed is a positive number
if isinstance(speed, (int, float)) and speed >= 0:
self.speed = speed
else:
raise ValueError("Speed must be a positive number")
def display_info(self):
print(f"Car brand: {self.brand}, Speed: {self.speed} km/h")
try:
# Attempting to create an object with invalid speed
car2 = SafeCar("Ford", -50)
car2.display_info()
except ValueError as e:
print("Error:", e)
Output:
Error: Speed must be a positive number
Here, we prevent invalid input by checking if speed
is a positive number. If not, an error is raised, and the program does not proceed with incorrect data.
Conclusion
Python classes allow us to encapsulate data and behavior into reusable objects. We covered:
- How to define a class and create an object.
- How to use methods to interact with object data.
- How to modify object attributes dynamically.
- How to handle errors within class methods.