Reputation: 31
I defined two __init__
methods inside a class as I mentioned in the code snippet
class Employee:
def __init__(self):
print('This is init method')
def __init__(self, workingHrs):
print('This is init method with parameter')
Now when we use this class
employee = Employee()
employee = Employee(1)
It gives this error:
Traceback (most recent call last):
File, line 20, in <module>
employee = Employee()
TypeError: __init__() missing 1 required positional argument: 'workingHrs'
My question is, how can I use both __init__
methods with and without parameter except for the self
parameter.
Upvotes: 3
Views: 52
Reputation: 152795
Python doesn't support method overloading so when two methods have the same name the second one will replace the first one.
This can be solved by using an optional argument:
class Employee(object):
def __init__(self, workingHrs=None):
if workingHrs is None:
print('This is init method')
else:
print('This is init method with parameter')
You could also use classmethod
s to "implement" different constructors.
Upvotes: 1