Hello so this is my first time learning about python, and i came across with constructor. Can someone please tell me why do we need the word 'self'. Here is the code: def init(self,n,p,i,):
Asked
Active
Viewed 56 times
-2
-
4Does this answer your question? [What is the purpose of the word 'self'?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self) – Humayun Ahmad Rajib Jul 16 '20 at 06:26
-
@HumayunAhmadRajib,thxx – Jonathan Alie Saputra Jul 16 '20 at 13:20
2 Answers
0
"self" means that one of the arguments for the constructor is the object itself. It seems counterintuitive to need an object to create an object, but the "self" being referred to when initializing the object instance is the new instance.
0
The word 'self' in a constructor represents the instance of a class. With this keyword, we can access the variables and functions inside a class. For example:
class foo:
'''Just an example'''
def __init__(self, person_name, person_age):
self.name = person_name
self.age = person_age
def fun(self):
''' We include the word "self" inside the function as an object to invoke the
fun() inside the class.'''
print("Name: {}".format(self.name))
print("Age : {}".format(self.age))
def display(self):
''' To display the name and age.'''
self.fun()
class_object = foo("John Doe", 30)
# The word 'self' isn't required when calling the function outside the class.
class_object.display()
# Name: John Doe
# Age : 30
This doesn't mean that the word 'self' is a reserved keyword in python. We can use any other word to represent an instance of the class. For example:
class foo:
'''Just an example again'''
def __init__(fun, person_name, person_age):
fun.name = person_name
fun.age = person_age
def display(fun):
print("Name: {}".format(fun.name))
print("Age : {}".format(fun.age))
class_object = foo("John Doe", 30)
class_object.display()
# Name: John Doe
# Age : 30

Abhishek Sriram
- 81
- 1
- 4