[英]How to fix 'object() takes no parameters' error when creating object?
我正在嘗試運行《Learn Python the Hard Way》一書中的程序,但它拋出了一個錯誤。 你能幫我解決我在這里做錯了什么嗎?
這是我收到的錯誤消息:
Traceback (most recent call last):
File "C:\Desktop\Python-testing\My-file.py", line 11, in
<module>
"So I'll stop right there"])
TypeError: object() takes no parameters
這是 Python 代碼:
class Song(object):
def _init_(self, lyrics):
self.lyrics=lyrics
def sing_me_a_song(self):
for line in self.lyrics:
print line
happy_bday = Song(["Happy birthday to you",
"I dont want to get sued",
"So I'll stop right there"])
bulls_on_parade = Song(["The rally around the family",
"with pockets ful of shales"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
在 python 中,初始化方法被命名為__init__
,而不是_init_
(兩個下划線而不是一個)。 所以方法定義
def _init_(self, lyrics):
只是定義了一個普通的方法,而不是覆蓋object.__init__
。 因此,當您使用參數初始化該類時, object.__init__(['Happy birthday...'])
被調用,並且失敗。
要解決此問題,請在每邊 2 個下划線(共 4 個)中寫入__init__
:
def __init__(self, lyrics):
你的構造函數應該是def __init__
而不是def _init_
。
Python 解釋器將def _init_
識別為普通函數,因此,它找不到構造函數,因此會出現“object() 不帶參數”的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.