0 votes
in Python by
How to overload constructors or methods in Python?

1 Answer

0 votes
by

Python's constructor: _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object. We can't overload constructors or methods in Python. It shows an error if we try to overload.

Example:

  1. class student:    
  2.     def __init__(self, name):    
  3.         self.name = name    
  4.     def __init__(self, name, email):    
  5.         self.name = name    
  6.         self.email = email    
  7.          
  8. # This line will generate an error    
  9. #st = student("rahul")    
  10.     
  11. # This line will call the second constructor    
  12. st = student("rahul""rahul@gmail.com")    
  13. print("Name: ", st.name)  
  14. print("Email id: ", st.email)  

Output:

Name:  rahul
Email id:  rahul@gmail.com
...