Self parameter and Constructor in Python

  • Self in Python is reference variable which always point toward current object inside the class.
  • Self is used to access instance variables and instance methods of object inside the class.
  • Whenever we create constructor and methods inside the class, it accepts self as a first parameter.
  • Self is used to create instance variables.
  1. class Student :
  2.     def __init__(self,name,age):
  3.         self.name=name       
  4.         self.age=age       # self.name and self.age is instance variable.
  5.     def display():
  6.         print('Name of student is '+self.name)   #calling instance variable by self parameter
  7.         print('Name of student is '+str(self.age)) 
  8. s1 = Student('ritesh',25)
  9. s1.display()
Constructor:
  • constructor is special method in Python which is automatically called when we create object of the class.
  • constructor is represented by __init__ method in Python.
  • It is used to declare and initialize instance variables.
  • In case we don't provide constructor then Python provide default constructor.
  • It is executed once at the time of object creation.

0 comments:

Post a Comment