- 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.
- class Student :
- def __init__(self,name,age):
- self.name=name
- self.age=age # self.name and self.age is instance variable.
- def display():
- print('Name of student is '+self.name) #calling instance variable by self parameter
- print('Name of student is '+str(self.age))
- s1 = Student('ritesh',25)
- 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