Why Python Uses 'Self' as Default Argument
In Python, when defining methods inside a class, first parameter is always self. It is not a keyword, but a naming convention that plays a key role in Python’s object-oriented programming.
The self parameter represents instance of the class itself, allowing you to access and modify its attributes and methods.
Example: This example shows how self is used to store data in an object and access it through methods.
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 method
print(car1.display())
Output
('Toyota', 'Corolla')
Explanation:
- self in __init__ assigns values (brand and model) to the specific instance (car1).
- self in display refers to the same instance (car1) to access attributes.
- Python automatically passes car1 as the first argument to display().
Now, Let's understand why python uses self.
Why use Self?
The main reason Python uses self is to make object-oriented programming explicit rather than implicit. By requiring the instance of the class as the first parameter, Python ensures:
- Clarity: Following Python’s “explicit is better than implicit” rule, it makes code easier to read.
- Flexibility: You can use any name (like this), but self is the standard.
- Consistency: Keeps all methods uniform across classes.
Why Not Implicit?
Unlike some other programming languages, Python doesn’t hide this reference automatically. This makes it clear and unambiguous that the method is operating on an instance of the class, which improves readability and avoids confusion (especially in inheritance).
Examples
Example 1: Object Initialization & Method Invocation
In this example, self is used to initialize an object’s topic and access it inside a method.
class gfg:
def __init__(self, topic):
self._topic = topic # Store parameter value in instance variable
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()
Output
Topic: Python
Explanation:
- self._topic = topic assigns "Python" to the instance ins.
- Inside topic(), self._topic refers to that stored value (Python automatically provides self when you call ins.topic()).
Example 2: Circle Class for Area Calculation
This example shows how self is used to access attributes of the correct instance while performing calculations.
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
Explanation:
- self.r = r assigns 5 as the radius of the circle instance ins.
- Inside area(), self.r ensures radius belongs to that specific circle (Python automatically provides self).
- This way, even if we create multiple circles with different radii, each object uses its own value of self.r.
What is the purpose of the self keyword in Python classes?
-
A
It refers to the class itself
-
B
It is used to define private methods
-
C
It refers to the current instance of the class
-
D
It refers to the superclass
self represents the instance of the class. It's used to access instance variables and methods from within the class.
What will be the output of the following code?
class MyClass:
def __init__(self, value):
self.value = value
def get(self):
return self.value
obj = MyClass(10)
print(obj.get())
-
A
None
-
B
Value
-
C
10
-
D
Error
The constructor initializes self.value with 10, and get() returns that value.
Why must self be the first parameter in instance methods?
-
A
It's required by the Python interpreter to distinguish instance methods
-
B
It's used for memory management
-
C
It's a syntax convention, not a requirement
-
D
It's only needed when inheriting from another class
The Python interpreter automatically passes the instance (self) as the first argument when calling instance methods.
What will happen if self is omitted from an instance method definition?
class Test:
def show():
print("Hello")
t = Test()
t.show()
-
A
Prints Hello
-
B
Raises TypeError
-
C
Prints nothing
-
D
Prints None
The method show() doesn't accept self, so when the instance t is used to call it, Python still passes self, causing a TypeError.
What will be the output of the following code?
class Sample:
def __init__(this, x):
this.x = x
def show(this):
print(this.x)
s = Sample(5)
s.show()
-
A
this
-
B
5
-
C
Error
-
D
None
Although this is used instead of self, it's just a parameter name. The code works and prints 5.
-
A
The class of the self instance
-
B
The parent class
-
C
The method name
-
D
The memory location of self
self.__class__ refers to the class to which the instance belongs, useful for introspection or logging.
