Member-only story
A class in Python
2 min readApr 2, 2024
A class in Python is a blueprint for creating objects. Classes encapsulate data and functions into a single logical unit. The data elements in a class (variables) are referred to as attributes, and the functions are called methods. Objects are instances of classes, each with its own distinct attributes and methods.
Example: Defining and Using a Class in Python
Let’s define a simple class named Car
that represents a car. It will have attributes to store its make, model, and year, and a method to display this information.
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def display_info(self):
print(f"Car Information: {self.year} {self.make} {self.model}")
# Creating an instance of the Car class
my_car = Car("Toyota", "Corolla", 2021)
# Accessing attributes
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Corolla
print(my_car.year) # Output: 2021
# Calling a method of the class
my_car.display_info() # Output: Car Information: 2021 Toyota Corolla
In this example:
Car
is the class that models the concept of a car.__init__
is a special method called a constructor. It's called when a new instance of the class is created, initializing the…