Classes and Objects in Python
In Python, classes and objects are the core components of object-oriented programming. A class is a blueprint or template for creating objects, while an object is an instance of a class. Let's explore classes and objects in more detail:
-
Class
A class is defined using the class keyword, followed by the class name. It contains attributes (variables) and methods (functions) that define the behavior and properties of objects created from that class. Here's an example of a simple class definition: -
Object
An object is an instance of a class. It represents a specific entity created based on the class definition. To create an object, you can use the class name followed by parentheses, optionally passing any required arguments to the constructor. Here's an example of creating an object of the Car class: -
Accessing Attributes and Methods
You can access attributes and methods of an object using the dot (.) notation. For example: -
Modifying Attributes
You can modify the attributes of an object by assigning new values to them. For example: -
Multiple Objects
You can create multiple objects (instances) of the same class, each with its own set of attributes and behavior. For example:
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
print("Engine started.")
In the above example, the Car class has two attributes (make and model) and a method (start_engine). The __init__ method is a special method called the constructor, which is executed when an object of the class is created.
my_car = Car("Toyota", "Camry")
In the above example, my_car is an object (instance) of the Car class. It has its own set of attributes (make and model) and can access the methods defined in the class.
print(my_car.make) # Output: Toyota
print(my_car.model) # Output: Camry
my_car.start_engine() # Output: Engine started.
In the above code, my_car.make and my_car.model access the attributes of the my_car object, while my_car.start_engine() calls the start_engine method.
my_car.make = "Honda"
my_car.model = "Accord"
your_car = Car("Ford", "Mustang")
In the above code, your_car is another object of the Car class, independent of the my_car object.
Classes and objects provide a way to organize code in a more structured and reusable manner. By defining classes, you can create objects that encapsulate data and behavior, making your code more modular and easier to manage.