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
Carclass has an__init__method (constructor) to initialize the attributesmake,model, andyear. Thedisplay_infomethod 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_caris an object of theCarclass. Thedisplay_infomethod is called on the object to display its details.
- Explanation: