Python: 如何摆脱这个 TypeError?
Python: How to get rid of this TypeError?
我正在测试我的面向对象编程文件:
class Animal():
def __init__(animal):
if animal == "dog":
print("Bark")
elif animal == "cat":
print("Meow")
elif animal == "cow":
print("Moo")
else:
print("No animal given")
它工作正常,但如果我这样做:
animal = Animal("dog")
它给我以下错误:
Traceback (most recent call last):
File "c:/Users/????/Desktop/Leahnn Files/testing/oop.py", line 12, in <module>
animal = Animal("dog")
TypeError: __init__() takes 1 positional argument but 2 were given
我该如何摆脱它?
传递给init
的第一个参数总是隐式构造的实例。你也应该在定义中处理这个:
def __init__(self, animal):
我正在测试我的面向对象编程文件:
class Animal():
def __init__(animal):
if animal == "dog":
print("Bark")
elif animal == "cat":
print("Meow")
elif animal == "cow":
print("Moo")
else:
print("No animal given")
它工作正常,但如果我这样做:
animal = Animal("dog")
它给我以下错误:
Traceback (most recent call last):
File "c:/Users/????/Desktop/Leahnn Files/testing/oop.py", line 12, in <module>
animal = Animal("dog")
TypeError: __init__() takes 1 positional argument but 2 were given
我该如何摆脱它?
传递给init
的第一个参数总是隐式构造的实例。你也应该在定义中处理这个:
def __init__(self, animal):