The reason behind the use of "self" instead of "this" in OOP in Python
Introduction
In this article, you'll learn how self
is used in Python, and why it is used instead of this
.
If you wanna jump to the answer, read the source directly by clicking here.
How self
is used in Python
In short, It's more of a convention used for representing the instance of a Class.
From the Official Python Documentation:
Often, the first argument of a method is called
self
. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.
Example:
class Person:
def __init__(self, name, age, pno):
self.name = name
self.age = age
self.pno = pno
def get_name(self):
print(self.name)
def get_age(self):
print(self.age)
def get_pno(self):
print(self.pno)
def set_name(self):
new_name = input("Enter New Name: ")
self.name = new_name
def set_age(self):
new_age = int(input("Enter New Age: "))
self.age = new_age
def set_pno(self):
new_pno = input("Enter New Phone Number: ")
self.pno = new_pno
def __repr__(self):
"""This method let's users print the details of the Person
when a user attempts to print the object."""
return f'{self.__class__.__name__}(name="{self.name}", age={self.age}, pno="{self.pno}")'
if __name__ == "__main__":
# Create an Object
jack = Person("Jack", 21, "+91-788888765")
print(jack)
# Update Phone Number
jack.set_pno()
# Update Age Number
jack.set_age()
# Print Phone Number
jack.get_pno()
print(jack)
# Output:
# Person(name="Jack", age=21, pno="+91-788888765")
# Enter New Phone Number:
# Input: +91-1234567890
# Output:
# Enter New Age:
# Input: 23
# Output:
# +91-1234567890
# Person(name="Jack", age=23, pno="+91-1234567890")
In the above example, self
is used for accessing the data members of the class. Also, I could have given some examples of how self
can be used for calling methods inside a class as well, but you'll be able to find plenty of them on the internet 😉.
Though, here's a must read answer about the purpose of the word self
in Python on Stack Overflow.
The Ultimate Question, Why self
instead of this
?
Students are curious why the first parameter to bound methods is
self
, notthis
. I'm guessing to make it clear that it doesn't actually work quite the same as this in other OO langs?
Tweeted by @pamelafox
The ANSWER
I don’t recall the reason I chose
self
, but I imagine it was an act of rebellion against C++this
. Just like ‘None’ rebelled against CNULL
. Basically just being a little ornery (like naming it after an irreverent tv show instead of a famous scientist or engineer).
Tweeted by Guido Van Rossum (Creator of Python)
Link to the Original Tweets
twitter.com/gvanrossum/status/1448523212329..
Read more about OOP in Python
docs.python.org/3/tutorial/classes.html