如何修复“ TypeError:printSong()缺少1个必需的位置参数:'self'”

时间:2019-06-25 14:23:05

标签: python

当我调用方法printSong()时,我收到一条错误消息:

“ TypeError:printSong()缺少1个必需的位置参数:'self'”

所以..我应该在括号内加上什么参数?

我可以从方法printSong()中删除“自我” ...但随后该方法将无法工作...

unique = {}
j = 0
for ix in range(len(Emden)-1):
    ux = [] #container for unique path
    branch = [] #container for branches
    for node in Emden["CPPath"][ix]:
        if node in Emden["CPPath"][ix+1]:
            if j not in unique.keys():
                unique[j] = [node]
            else:
                unique[j].append(node)
    j+=1

final = []
for ix in range(len(unique)-1):
    for j in unique[ix]:
        if j in unique[ix+1] and not j in row:
            row.append(j)

我希望主页仅列出第一首歌曲“ Gloria”的信息, 相反,我收到一条错误消息:

内部服务器错误 服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序错误。

2 个答案:

答案 0 :(得分:1)

您尚未实例化课程:

songs[1] = song() # need the parentheses here

否则,song没有self属性,因为从未调用过__init__

s = song

# s is the class song, not an instance
s
<class '__main__.song'>

s.printSong()
# raises error because printSong is an instance method, but because
# you aren't calling this from an instance of the class, the instance
# isn't available to the method

s = song()
s
<__main__.song object at 0x10d7dbef0>
# Now s is an instance, and you can call instance methods because
# they have access to self

答案 1 :(得分:0)

将行更改为歌曲[1] = song()

class song:
    def __init__(self):
        self.title = ""
        self.artist = ""

    def printSong(self):
        return "The song " + self.title + " is song by " + self.artist

songs = {}

songs[1] = song()

songs[1].title = "Gloria"
songs[1].artist = "U2"



songs[1].printSong()


'The song Gloria is song by U2'