Classes and Objects in Python
Classes and Objects
72
In Python, classes and objects are the building blocks of object-oriented programming. Classes encapsulate data and methods (functions) that act upon that data. When a class is created, it becomes a blueprint for creating new objects, which are instances of that class.
Here's an example of a Python class:
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def drive(self): print(f"The {self.make} {self.model} is driving.")
In this example, the class is called Car
. It has three attributes: make
, model
, and year
. These attributes are set using the __init__
method, which is called when a new object is created. The self
parameter refers to the object being created.
The class also has one method, drive()
, which prints a message indicating that the car is driving.
To create a new instance of the Car class, you would do something like this:
my_car = Car("Honda", "Civic", 2020)
This creates a new object called my_car
using the arguments "Honda", "Civic", and 2020 for the make, model, and year attributes, respectively.
You can then call the drive()
method on the my_car
object:
my_car.drive()
This will print out the message "The Honda Civic is driving."
Object-oriented programming with classes and objects allows you to organize your code in a logical and modular way, making it easier to manage and extend as your program grows.
March 25, 2023