Classes and Objects

What are Classes and Objects?

Object-Oriented Programming (OOP) revolves around two main concepts: classes and objects.

  • Class: A blueprint or template for creating objects. It defines properties (attributes) and behaviors (methods).
  • Object: An instance of a class with actual values assigned to its attributes.

Defining a Class in Python

In Python, we define a class using the class keyword:

class Car:
    def __init__(self, brand, model, year):
        self.brand = brand
        self.model = model
        self.year = year

    def display_info(self):
        print(f"{self.year} {self.brand} {self.model}")

# Creating an object (instance) of the class
my_car = Car("Toyota", "Corolla", 2022)

# Accessing attributes and methods
print(my_car.brand)  # Output: Toyota
my_car.display_info()  # Output: 2022 Toyota Corolla

Understanding the __init__() Method

  • The __init__() method is a special method (constructor) that initializes an object when it is created.
  • self refers to the instance of the class and is used to access attributes and methods.

Creating Multiple Objects

You can create multiple objects from the same class:

car1 = Car("Honda", "Civic", 2023)
car2 = Car("Ford", "Mustang", 2021)

car1.display_info()  # Output: 2023 Honda Civic
car2.display_info()  # Output: 2021 Ford Mustang

Modifying Object Attributes

Attributes of an object can be modified after creation:

my_car.year = 2023
print(my_car.year)  # Output: 2023

Deleting Object Attributes

You can delete an attribute using del:

del my_car.year

Checking an Object’s Type

To check the type of an object:

print(isinstance(my_car, Car))  # Output: True

Summary

Classes define a blueprint for objects.
Objects are instances of a class.
The __init__() method initializes objects.
Methods define behaviors, and attributes store data.
Multiple objects can be created from the same class.