Introduction
Python is an object-oriented programming (OOP) language, meaning it allows us to define and manipulate classes and objects. Classes serve as blueprints for creating objects, while objects are instances of those classes. Understanding how to create and use Python classes and objects is essential for writing efficient and reusable code.
Objective
In this tutorial, we will cover how to:
- Create a class in Python
- Instantiate objects from a class
- Access and modify object attributes
- Define methods within a class
Python Code Example
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def description(self): return f"{self.year} {self.make} {self.model}" def start_engine(self): return f"The {self.make} {self.model}'s engine is now running." # Creating an object (instance) of the class 'Car' my_car = Car("Toyota", "Corolla", 2020) # Accessing attributes of the object print(my_car.description()) # Calling a method from the object print(my_car.start_engine())
Program Explanation
The program above demonstrates how to create a class, instantiate objects, and define methods. Here’s a breakdown of the program structure:
- Class Definition: The class
Car
is defined with an__init__
method, which is the constructor. It initializes the attributesmake
,model
, andyear
for each object. - Instance Creation: An object
my_car
is created by calling the classCar
with arguments for make, model, and year. - Method Definition: The
description
andstart_engine
methods are defined within the class to operate on the object’s data. - Object Usage: The object
my_car
is used to call the methods and access its attributes. We print out the description and call thestart_engine
method to simulate starting the car.
How to Run the Program
To run this program:
- Save the code in a file with a
.py
extension, for example,car_program.py
. - Open a terminal or command prompt.
- Navigate to the folder where the Python file is saved.
- Run the program by typing
python car_program.py
(orpython3 car_program.py
depending on your setup).