Overwriting init() in python. TypeError: __init__() takes 1 positional argument but 3 were given
Overwriting init() in python. TypeError: __init__() takes 1 positional argument but 3 were given
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)
我希望输出为:
a:乔治 b:25000
a:约翰 b:30000
3
但是我收到这个错误:
TypeError: init() 采用 1 个位置参数,但给出了 3 个
帮助初学者
谢谢。
Python class.
中不能有重载方法
这将导致仅第二个 __init__
保留,第一个将被丢弃:
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
您可以使用参数默认值实现几乎相同的功能:
def __init__(self, a=None, b=None):
self.a = a
self.b = b
A.x += 1
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)
我希望输出为:
a:乔治 b:25000
a:约翰 b:30000
3
但是我收到这个错误:
TypeError: init() 采用 1 个位置参数,但给出了 3 个
帮助初学者
谢谢。
Python class.
中不能有重载方法这将导致仅第二个 __init__
保留,第一个将被丢弃:
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
您可以使用参数默认值实现几乎相同的功能:
def __init__(self, a=None, b=None):
self.a = a
self.b = b
A.x += 1