Classes and Objects in Python

  • Last updated Apr 25, 2024

In Python, a class is a blueprint for creating objects and an object is an instance of a class.

Creating a Class

The class defines the structure and behavior of an object.

In Python, a class is created using the class keyword followed by the class name and a colon. Inside the class body, you can define attributes and functions that describe the behavior of objects created from the class.

Here's a simple class definition:

class Student:
    def __init__(self, firstname, lastname, age):
        self.firstname = firstname
        self.lastname =  lastname
        self.age = age

    def add_user(self):
        print("Adding user...")
        # Logic to add a new user

    def update_user(self):
        print("Updating user...")
        # Logic to update an existing user

In this example, we have defined a Student class with attributes: firstname, lastname, age, and functions add_user and update_user. The self parameter is used to represent the current instance of the class which helps to access properties and methods of the class.

Creating an Object

An object is an instance created from a class.

In Python, every class has the __init__() function and is executed while creating an object of a class. The __init__() function is a built-in Python function that is used as a constructor of the class to initialize properties of the class or to perform other operations that needs to be executed while creating an object.

Once a class is defined, you can create objects or instances of that class by invoking the class as if it were a function, and passing any necessary arguments to the class's constructor.

Here's an example of creating objects:

student1 = Student("Danny", "A", 28)
student2 = Student("Johny", "B", 30)

In this example, we created two Student objects, student1 and student2, with different values for the firstname, lastname, and age attributes.

Accessing Attributes and Methods

In Python, attributes and methods of an object can be accessed using dot notation.

Here's an example of accessing attributes and methods of an object:

# Accessing attributes

# Accessing methods

Classes and objects are fundamental concepts in object-oriented programming, and they allow you to model and represent real-world entities and their behaviors in a structured and reusable way.