2016-12-14 41 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'