About Lesson
Classes and Objects
Defining Classes and Creating Objects
- Class Definition: A class is a blueprint for creating objects. It defines a set of attributes and methods that the objects created from the class will have. python
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def display_info(self): print(f"{self.year} {self.make} {self.model}")
- Explanation: The
Car
class has an__init__
method (constructor) to initialize the attributesmake
,model
, andyear
. Thedisplay_info
method prints the car’s details.
- Explanation: The
Creating Objects:
- Object Creation: An object is an instance of a class. You create an object by calling the class. python
my_car = Car("Toyota", "Corolla", 2020) my_car.display_info() # Output: 2020 Toyota Corolla
- Explanation:
my_car
is an object of theCar
class. Thedisplay_info
method is called on the object to display its details.
- Explanation: