NEXT TUTORIAL >> init method in class
self variable in Python class is a default variable that acts as an instance of a python class. With the help of self variable, we can access the attributes as well as methods of a class.
Whenever an instance to the class is created, the instance name contains the memory address of the instance. This memory address is internally passed to self.
Let us consider an example :
a = Animal()
Here, ‘a’ holds the memory address of the instance (class Animal). This address, by default, is passed to self variable. Once passed, ‘self’ has the address details of the instance and hence can use it to refer to all attributes of the instance(class).
Let’s try to see whether our instance and ‘self’ variable points to same memory location,
class Main:
def __init__(self):
print('Address in self: ', id(self))
main = Main() # main is the instance of class Main
print('Address in main: ',id(main))
O/P
Address in self: 140296906646720
Address in main: 140296906646720
Self is the first thing…
The self variable is the first parameter to be passed in the constructor or an instance method.
If we somehow forget to include this self variable, we will be smashed with a TypeError. Let’s see how
class Main:
def __init__():
print('This will not print')
main = Main() # main is the instance of class Main
O/P
TypeError: init() takes 0 positional arguments but 1 was given.
Also, self variable is used by instance methods to act on the instance variables of the class. Let’s see how
class Main:
def __init__(self, name):
self.name = name
def display(self):
print('What`s in self ?', self) # object containing memory location
print('Your name is ', self.name)
main = Main('Mojo Jojo') # calling a class Main with name as 'Mojo Jojo'
main.display()
# main is the instance of class Main
O/P
What`s in self ? <main.Main object at 0x7f0a847234c0>
Your name is Mojo Jojo
In the above code, we bounded the variable ‘name’ to self which can now be accessed by instance method ‘display()’ as self.name.
But self can be anything you want…
This means that you can write any name as per your choice in place of self. Like,
class Main:
def __init__(codeofgeeks): # Using new name instead of self
print('I gave self a new name')
main = Main() # main is the instance of class Main
O/P
I gave self a new name
That’s all here.
NEXT TUTORIAL >> init method in class
