3.
2 Classes and Objects
Understanding the foundation of
Object-Oriented Programming (OOP)
What are Classes and Objects?
• - **Class**: A blueprint for creating objects.
• - **Object**: An instance of a class with
attributes and behaviors.
• - Classes define properties (variables) and
methods (functions).
• - Objects store data and can perform actions.
Defining a Class in Python
• Example:
• class Car:
• def __init__(self, brand, model):
• self.brand = brand
• self.model = model
• def display_info(self):
• return f'{self.brand} {self.model}'
• my_car = Car('Toyota', 'Corolla')
• print(my_car.display_info()) # Output: Toyota Corolla
Creating and Using Objects
• - Objects are instances of a class.
• - Each object has its own attributes and can execute
class methods.
• - Example:
• car1 = Car('Ford', 'Mustang')
• car2 = Car('Honda', 'Civic')
• print(car1.display_info()) # Output: Ford Mustang
• print(car2.display_info()) # Output: Honda Civic
Class Methods vs Instance Methods
• - **Instance Methods**: Operate on individual object instances.
• - **Class Methods**: Use `@classmethod` and can modify class attributes.
• - Example:
• class Vehicle:
• total_vehicles = 0
• def __init__(self, type):
• self.type = type
• Vehicle.total_vehicles += 1
• @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.