Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

python - How to fix 'object() takes no parameters' error when creating object?

I am trying to run the program from the book Learn Python the Hard Way but it's throwing an error. Could you please help me on what I am doing wrong here?

This is the error message I'm getting:

Traceback (most recent call last):
  File "C:DesktopPython-testingMy-file.py", line 11, in 
<module>
    "So I'll stop right there"])
TypeError: object() takes no parameters

This is the Python Code:

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In python, the initializer method is named __init__, not _init_ (two underscores instead of one). So the method definition

def _init_(self, lyrics):

just defines an ordinary method, instead of overriding object.__init__. Therefore, when you initialize the class with an argument, object.__init__(['Happy birthday...']) gets called, and that fails.

To fix this problem, write __init__ with 2 underscores at each side (4 total):

def __init__(self, lyrics):

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...