Python中的类-TypeError:object()不接受参数

2024-05-14 20:29:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还不太熟悉,我在使用这一点代码时遇到了问题。我总是碰到同样的问题。运行此命令时,会收到错误消息:

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()

error message


Tags: 代码self消息deftype错误displayclass
2条回答

Bird类中没有__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类中没有接受此参数的__init__()函数。您的Bird类应该如下:

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)

相关问题 更多 >

    热门问题