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}'
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
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
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
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.