2016-12-14 37 views
-3

我是python的新手,并且遇到了让代码工作的问题。我一直在遇到同样的问题。当我运行这个时,我收到错误信息:Python中的类 - TypeError:object()不带参数

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

+0

您对如何声明构造函数感到困惑。在python中,你使用'__init__'而不是类的名字。即使iy是那样,为什么一个类'Bird'有一个构造函数'bird'? –

+0

https://stackoverflow.com/questions/27078742/typeerror-object-takes-no-parameters – kta

回答

1

在代码中,你正在做的:

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) 
+0

谢谢。这解决了这个问题。但是现在我得到一个新的错误:Traceback(最近一次调用最后一次): 文件“/Users/MNK/Documents/hack.py”,第35行,在 main() 文件“/ Users/MNK /文件/ hack.py“,第32行,在主 species.display() 文件”/Users/MNK/Documents/hack.py“,第21行,在显示中 self._bird.display(self) TypeError :display()需要1个位置参数,但给出了2个 – Matthew

+0

请为此创建一个单独的问题。另请注意,Python注意Python不是Java。你不需要setter和getter函数 –

+0

@Matthew:关于你的新错误,用self._bird.display()替换'self._bird.display(self)'' –

0

你没有你的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'