How To Create Classes and Objects In Python?

Published On: Wed, 29 Nov 2023 Updated On: Wed, 29 Nov 2023

Mastering Object-Oriented Programming in Python: Classes and Objects

Python, a versatile and powerful programming language, supports object-oriented programming (OOP) paradigms. OOP allows developers to organize code into reusable and modular structures called classes. These classes act as blueprints to create objects, which are instances of those classes. In this blog, we will dive into the world of classes and objects in Python, understanding their attributes, methods, constructors, and destructors, and exploring class composition and aggregation with practical examples.

Defining Classes and Creating Objects in Python

A class is a user-defined data type that encapsulates data and methods that operate on that data. It serves as a skeleton for creating objects. To define a class in Python, we use the class keyword. Let's create a simple class Car:

Code Example

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

    def display_info(self):
        return f"Car: {self.make} {self.model}"

 

In this example, we have defined a class Car with two instance attributes (make and model) and a method display_info() that returns information about the car.

To create an object (instance) of the Car class, we use the class name followed by parentheses:

Code Example

car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")    

 

Class Attributes, Instance Attributes, and Methods

All instances share class attributes among themselves. They are defined within the class but outside any method. Instance attributes, however, are specific to each class instance and are defined inside the constructor method __init__.

Code Example

class Dog:
    species = "Canine"  # Class attribute

    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age    # Instance attribute

    def bark(self):
        return "Woof!"

 

In this example, species is a class attribute, while name and age are instance attributes. We can access class and instance attributes using the dot notation:

Code Example

dog1 = Dog("Buddy", 3)
print(dog1.species)  # Output: "Canine"
print(dog1.name)     # Output: "Buddy"
print(dog1.age)      # Output: 3

 

Constructor and Destructor Methods

The constructor method __init__ is called when an object is created. It initializes the object's attributes. Similarly, the destructor method __del__ is called when the object is about to be destroyed.

Code Example

class Person:
    def __init__(self, name):
        self.name = name
        print(f"{self.name} has been created.")

    def __del__(self):
        print(f"{self.name} has been deleted.")

 

Now, let's create a couple of Person objects:

Code Example

person1 = Person("Alice")
person2 = Person("Bob")

 

Upon running this code, we will see the following output:

Code Example

bash $
Alice has been created.
Bob has been created.
bash $

 

When these objects go out of scope or are explicitly deleted, the destructor will be called:

Code Example

del person1
del person2

 

The output will be:

Code Example

bash $
Alice has been deleted.
Bob has been deleted.
bash $

 

Class Composition and Aggregation

Class composition and aggregation are two fundamental concepts in OOP. Composition refers to a class containing objects of other classes, and the container class controls the lifetime of the contained objects. Conversely, aggregation is a weaker relationship, where the objects can exist independently outside the container class.

Let's understand this with an example of an Author and Book class:

Code Example

class Author:
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return self.name

class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def display_info(self):
        return f"{self.title} by {self.author}"

 

In this example, the Author class is composed within the Book class, as a book cannot exist without an author. The Author class has no reference to the Book class, making it an aggregation.

Let's create objects for demonstration:

Code Example

author1 = Author("J.K. Rowling")
book1 = Book("Harry Potter and the Sorcerer's Stone", author1)

print(book1.display_info())  # Output: "Harry Potter and the Sorcerer's Stone by J.K. Rowling"

 

Conclusion

Python's support for classes and objects enables developers to create organized and efficient code. With classes, attributes, methods, constructors, and destructors, you can build complex programs in a modular and reusable manner. Additionally, class composition and aggregation enhance the flexibility and maintainability of your code. As you delve deeper into object-oriented programming, you'll find endless possibilities to create robust and elegant solutions to various programming challenges.

How To Create Classes and Objects In Python?

Reader Comments


Add a Comment