Self in Python class

Self in Python Class: 

Self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments. It is just like this pointer in c++.  The self method is explicitly used every time we define a method. In this article, we will get to know about self in Python class.
Self in Python Class

Self : 

  •  The reason why we use self is that Python does not use the ‘@’ syntax to refer to instance attributes. In Python, we have methods that make the instance to be passed automatically, but not received automatically. 
  • self is used in different places and often thought to be a keyword. But unlike in c++, self is not a keyword in Python.

Code #1 ( self in __init__ Function):

#python Program
#Rishikesh 

 
class PrepInsta:
    def __init__(self,name):
        self.name=name 
        print(‘You are in Parent class’)

ob1=PrepInsta(‘rishikesh’##object 
print(ob1.name)

Output: 

You are in Parent class
rishikesh

Code #2 ( self in Function):

#python Program
#Rishikesh 

 
class PrepInsta:
    def __init__(self,name):
        self.name=name 
        #print(‘You are in Parent class’)
    def display(self):
        print(self.name)
        print(‘U are in Display Function ‘)
ob1=PrepInsta(‘rishikesh’##object 
ob1.display()

Output: 

rishikesh
U are in Display Function