What is ‘Self’ in Python With Example

In Python, self is a conventional name used to refer to the instance of a class within the class’s methods. It allows accessing the attributes and methods of the current object. When defining a class method, the first parameter is typically named self (although you can choose a different name), and it represents the instance on which the method is called.

Here’s an example to illustrate the use of self in Python:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

    def celebrate_birthday(self):
        self.age += 1
        print(f"Happy birthday! Now I am {self.age} years old.")


# Creating an instance of the Person class
john = Person("John", 25)

# Accessing attributes using 'self'
print(john.name)  # Output: John
print(john.age)   # Output: 25

# Calling methods using 'self'
john.introduce()  # Output: My name is John and I am 25 years old.
john.celebrate_birthday()  # Output: Happy birthday! Now I am 26 years old.
Code language: Python (python)

In the example above, the self parameter is used to access and modify the name and age attributes of the Person instance (john). The self.introduce() method uses self.name and self.age to introduce the person. Similarly, the self.celebrate_birthday() method increments the person’s age by 1 using self.age.

By convention, the self parameter is used within class methods, but it is not required to use the name self. However, it is recommended to use it as it improves code readability and makes it easier to understand the purpose of the parameter.

Read More;

  • I am a middle python software engineer with a bachelor's degree in Software Engineering from Kharkiv National Aerospace University. My expertise lies in Python, Django, Flask, Docker, REST API, Odoo development, relational databases, and web development. I am passionate about creating efficient and scalable software solutions that drive innovation in the industry.

    View all posts

Leave a Comment