First time here? Checkout the FAQ!
x
+1 vote
550 views
asked in Python Interview Questions by (1.4k points)  
  

1 Answer

+1 vote
answered by (1.4k points)  

Self is an instance or an object of a class. The name self is a convention and can be replaced by any other variable name. The first parameter is considered as "self". In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a class with local variables. 
The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called. 

_init_ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/instance of a class is created. All classes have the _init_ method. 
Here is an example of how to use it:

class Employee:
    def _init_(self, name, age.salary): 
        self.name= name 
        self.age = age 
        self.salary = 20000 

El = Employee('XYZ', 23, 20000) 
# El is the instance of class Employee. 
# _init_ allocates memory for El. 
print(El.name)
#Output: 'XYZ'
print(El.age)
#Output: 23
print(El.salary) 
#Output: 20000
...