self and __init__ in Object oriented Python
Let's first observe below Python code
# Python code for planet name, radius and it's distance from the star.
class Planet:
def __init__ (self, name, radius, distance): # constructor
self.name = name
self.radius= radius
self.distance=distance
def system (self):
print ("Name of the planet: ", self.name)
print ("Radius of the planet: ", self.radius)
print ("Distance from the star: ", self.distamce)
p1 = Planet (Jupiter, 69911, 757.4)
# declaration of object 1
p2 = Planet (Neptune, 24,622, 4.4756)
# declaration of object 2
print ("Name of the planet: ",p1.name)
print ("Radius of the planet: ",p1.radius)
print ("Distance from the star: ",p1.distance)
#******************************************
p1.system (Jupiter, 69911, 757.4)
# calling the system method
p2.system (Neptune, 24622, 4.4756)
# calling the system method
In above code
self is the reference variable always pointing to the current object
self is not a Python keyword it is just a convention
self is use to access instance variable inside the class
Inside self.name, self.radius, self.distance is used to access the instance variables
Outside the class p1.name, p1.radius, p2.distance is used to access the instance variables
In java "this" keyword is used to access instance variables
__init__ is the special type of method called constructor
It is used for declaration and initialisation of instance variables
__init__ means initialisation
Instance variables are those variables which are change from object to object
In above code "name", "radius", "distance" are the instance variables
for example in p1 object planet name is Jupiter, radius is 69911 and distance is 757.4
whereas in p2 object planet name is Neptune, radius is 24622 and distance is
4.4756
you can see clearly that the value of instance variables is different in both objects p1 and p2
Thank you
Author YASH SHRIMALI
Technology Practitioner
Comments
Post a Comment