Why Python Uses 'Self' as Default Argument (original) (raw)

Last Updated : 11 Dec, 2024

In Python, when defining methods within a class, the first parameter is always self. The parameter self is a convention not a keyword and it plays a key role in Python’s object-oriented structure.

**Example:

Python `

class Car: def init(self, brand, model): self.brand = brand # Set instance attribute self.model = model # Set instance attribute

def display(self):
    return self.brand, self.model

Create an instance of Car

car1 = Car("Toyota", "Corolla")

Call the display_info method

print(car1.display()) # Output: This car is a Toyota Corolla

`

Output

('Toyota', 'Corolla')

**Explanation:

Let's understand the use of self as default argument in python in detail:

Why Python Uses 'Self' As Default Argument?

The main reason Python uses self as the default argument is to make object-oriented programming explicit rather than implicit. By requiring the instance of the class to be passed explicitly as the first parameter to every instance method, Python ensures that the code is clear and unambiguous. This explicit approach makes it immediately obvious that methods are operating on an instance of the class, which enhances code readability and avoids confusion, especially in complex inheritance scenarios.

Why Not Implicit?

Unlike some other programming languages, Python requires self explicitly because:

Below, are the example of using 'Self' As A Default Argument in Python.

Example 1: Object Initialization & Method Invocation

Python `

class gfg: def init(self, topic): self._topic = topic # Rename the instance variable to avoid conflict

def topic(self):
    print("Topic:", self._topic)  # Access the renamed variable

Creating an instance of gfg

ins = gfg("Python")

Calling the topic method

ins.topic()

`

**Explanation: In this example, 'self' is used to refer to the instance of the class, 'ins.' Without the explicit use of 'self,' it would be unclear which instance the method is referring to and the code might become ambiguous.

Example 2: Circle Class for Area Calculation Example

In this example, 'self' is crucial for accessing the ****'r'** attribute of the specific instance '**ins.' The use of ****'self'** ensures that the method operates on the attributes of the correct instance.

Python `

class Circle: def init(self, r): self.r = r

def area(self):
    a = 3.14 * self.r ** 2
    return a

Creating an instance of Circle

ins = Circle(5)

Calling the area method

print("Area of the circle:", ins.area())

`

Output

Area of the circle: 78.5