Reputation: 5
class A:
x = 0
def __init__(self, a, b):
self.a = a
self.b = b
A.x += 1
def __init__(self):
A.x += 1
def displayCount(self):
print('Count : %d' % A.x)
def display(self):
print('a :', self.a, ' b :', self.b)
a1 = A('George', 25000)
a2 = A('John', 30000)
a3 = A()
a1.display()
a2.display()
print(A.x)
I expect output as:
a : George b : 25000
a : John b : 30000
3
But I'm getting this error:
TypeError: init() takes 1 positional argument but 3 were given
Help out a beginner
Thanks.
Upvotes: 0
Views: 857
Reputation: 24038
You can't have overloaded methods in a Python class.
This will result in just the second __init__
staying around and the first one will be discarded:
def __init__(self, a, b): # Will get shadowed and thrown away.
self.a = a
self.b = b
A.x += 1
def __init__(self): # Only this one will be left in the class.
A.x += 1
You can achieve pretty much the same functionality with parameter defaults:
def __init__(self, a=None, b=None):
self.a = a
self.b = b
A.x += 1
Upvotes: 1