Classes_and_Objects 14
Classes_and_Objects 14
• class Car:
• def __init__(self, brand, model):
• self.brand = brand
• self.model = model
• def display_info(self):
• return f'{self.brand} {self.model}'
• class Vehicle:
• total_vehicles = 0
• @classmethod
• def get_total_vehicles(cls):
• return cls.total_vehicles
• print(Vehicle.get_total_vehicles()) # Output: 0
• v1 = Vehicle('Car')
• print(Vehicle.get_total_vehicles()) # Output: 1
Constructors and Destructors
• - **Constructor (`__init__`)**: Initializes an object.
• - **Destructor (`__del__`)**: Cleans up resources when an object is deleted.
• - Example:
• class Example:
• def __init__(self, name):
• self.name = name
• print(f'Object {name} created')
• def __del__(self):
• print(f'Object {self.name} deleted')
• obj = Example('Test')
• del obj # Output: Object Test deleted
Conclusion
• - **Classes** define the structure and
behavior of objects.
• - **Objects** are instances of a class that
store data and perform actions.
• - Understanding classes and objects is
essential for Object-Oriented Programming.