The constructor of Python: _ A class’s init__ () method is the first one. Python automatically calls __init__() to initialize object members whenever we attempt to instantiate an object. In Python, we can’t overload constructors or methods. If we attempt to overload, it displays an error.
Example:
- class student:
- def __init__(self, name):
- self.name = name
- def __init__(self, name, email):
- self.name = name
- self.email = email
- # This line will generate an error
- #st = student(“rahul”)
- # This line will call the second constructor
- st = student(“rahul”, “rahul@gmail.com”)
- print(“Name: “, st.name)
- print(“Email id: “, st.email)
Output:
Name: rahul Email id: rahul@gmail.com