The self Variable in Python

Published Aug. 3, 2023, 1:25 p.m.

In Python, the self variable is a default reference that always points to the current object (similar to the this keyword in Java). It allows us to access instance variables and instance methods of the object. The self variable should always be the first parameter inside the constructor (__init__(self)) and instance methods (def talk(self):).

Example: Using the self Variable

Let's create a simple class called Person to demonstrate the usage of the self variable.

class Person:
    def __init__(self, name, age):
        # Constructor with `self` as the first parameter
        self.name = name
        self.age = age

    def talk(self, message):
        # Method with `self` as the first parameter
        return f"{self.name} says: {message}"

Creating an Instance and Accessing Instance Variables and Methods

Now, let's create an instance of the Person class and use the self variable to access instance variables and call instance methods.

# Create an instance of the Person class
person1 = Person("Alice", 30)

# Access instance variables using `self`
print(person1.name)  # Output: Alice
print(person1.age)   # Output: 30

# Call instance method using `self`
message = person1.talk("Hello, nice to meet you!")
print(message)  # Output: Alice says: Hello, nice to meet you!

Explanation:

  1. We define a class Person with a constructor (__init__) that takes three parameters: selfname, and age. The self parameter is mandatory and represents the instance of the class.

  2. Inside the constructor, we use the self variable to initialize the instance variables name and age with the values provided as arguments during object creation.

  3. We define an instance method talk() that also takes self as the first parameter, along with an additional parameter message. The self parameter is necessary to access the instance variables and other methods of the object.

  4. We create an instance of the Person class called person1 with the name "Alice" and age 30.

  5. We use the self variable to access the instance variables name and age of person1 using dot notation (person1.nameperson1.age).

  6. We call the talk() method on person1 using the self variable, passing the message "Hello, nice to meet you!". The method uses self.name to retrieve the name of the person and combines it with the provided message to generate the output.

The self variable is crucial in Python classes as it allows us to work with specific instance data, making it possible to create multiple objects with different attributes and behaviors within the same class blueprint.