Classes in Python - TypeError: object() takes no parameters
Classes in Python - TypeError: object() takes no parameters
我是 python 的新手,我在使用这段代码时遇到了问题。我一直 运行ning 关注同样的问题。当我 运行 时,我收到错误消息:
TypeError: object() takes no parameters.
我已在下面包含完整的错误消息。
这是我的代码:
class Bird:
_type = ""
def bird(self, type):
self._type = type
def display(self):
print(self._type)
class Species:
_bird = None
_type = ""
def set_bird(self, bird):
self._bird = bird
def display(self):
print(self._type)
self._bird.display(self)
class Cardinal(Species):
def cardinal(self):
self._type = "Cardinal"
def main():
species = Cardinal()
species.set_bird(Bird("Red"))
species.display()
main()
你的 Bird
class 中没有 __init__()
函数,所以你不能写:
Bird("Red")
如果你想传递这样的参数,你需要做:
class Bird:
def __init__(self, color):
self.color = color
# The rest of your code here
下面,你可以看到结果:
>>> class Bird:
... def __init__(self, color):
... self.color = color
...
>>>
>>>
>>> b = Bird('Red')
>>> b.color
'Red'
在您的代码中,您正在做:
species.set_bird(Bird("Red"))
创建 Bird
的对象时,您正在传递参数 "Red"
。但是Bird
class中没有__init__()
函数接受这个说法。你的 Bird
class 应该是这样的:
class Bird:
# _type = "" <--- Not needed
# Probably you miss understood it with the
# part needed in `__init__()`
def __init__(self, type):
self._type = type
def bird(self, type):
self._type = type
def display(self):
print(self._type)
我是 python 的新手,我在使用这段代码时遇到了问题。我一直 运行ning 关注同样的问题。当我 运行 时,我收到错误消息:
TypeError: object() takes no parameters.
我已在下面包含完整的错误消息。
这是我的代码:
class Bird:
_type = ""
def bird(self, type):
self._type = type
def display(self):
print(self._type)
class Species:
_bird = None
_type = ""
def set_bird(self, bird):
self._bird = bird
def display(self):
print(self._type)
self._bird.display(self)
class Cardinal(Species):
def cardinal(self):
self._type = "Cardinal"
def main():
species = Cardinal()
species.set_bird(Bird("Red"))
species.display()
main()
你的 Bird
class 中没有 __init__()
函数,所以你不能写:
Bird("Red")
如果你想传递这样的参数,你需要做:
class Bird:
def __init__(self, color):
self.color = color
# The rest of your code here
下面,你可以看到结果:
>>> class Bird:
... def __init__(self, color):
... self.color = color
...
>>>
>>>
>>> b = Bird('Red')
>>> b.color
'Red'
在您的代码中,您正在做:
species.set_bird(Bird("Red"))
创建 Bird
的对象时,您正在传递参数 "Red"
。但是Bird
class中没有__init__()
函数接受这个说法。你的 Bird
class 应该是这样的:
class Bird:
# _type = "" <--- Not needed
# Probably you miss understood it with the
# part needed in `__init__()`
def __init__(self, type):
self._type = type
def bird(self, type):
self._type = type
def display(self):
print(self._type)