Classes and Objects in Python

In Python, a class is a blueprint or a template for creating objects, which are instances of the class. An object is an instance of a class that can have its own attributes (variables) and methods (functions).

Here’s an example of a simple class in Python:

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

    def info(self):
        print(f"{self.make} {self.model} ({self.year})")

In this example, the Car class has three attributes (make, model, and year) and one method (info). The __init__ method is a special method in Python that is called when a new object is created. It takes in arguments make, model, and year and assigns them to the corresponding attributes of the new object.

The info method simply prints out information about the car’s make, model, and year.

Here’s an example of how to create an object of the Car class and use its attributes and methods:

my_car = Car("Toyota", "Camry", 2022)
my_car.info()  # prints "Toyota Camry (2022)"

In this example, we create a new object of the Car class with the make “Toyota”, model “Camry”, and year 2022. We then call the info method on this object, which prints out information about the car.

Delete the Object:

In Python, you can delete an object by using the del statement. Here’s an example:

my_car = Car("Toyota", "Camry", 2022)
del my_car

In this example, we create a new object of the Car class and assign it to the variable my_car. We then use the del statement to delete the my_car object. After this statement is executed, the my_car variable no longer references the object, and the object will be deleted from memory by the Python interpreter’s garbage collector.

Note that when you delete an object, Python automatically calls the object’s __del__ method if it exists. This method can be used to perform any necessary cleanup operations before the object is deleted. Here’s an example of a Car class with a __del__ method:

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

    def info(self):
        print(f"{self.make} {self.model} ({self.year})")

    def __del__(self):
        print(f"Deleting {self.make} {self.model}")

In this example, the __del__ method simply prints out a message indicating that the car is being deleted. If we create a Car object and then delete it, we’ll see this message printed:

my_car = Car("Toyota", "Camry", 2022)
del my_car  # prints "Deleting Toyota Camry"