“list”对象没有属性“info”

2024-05-16 08:51:53 发布

您现在位置:Python中文网/ 问答频道 /正文

在一个类中,我有以下代码:

class Player (object):
    def __init__ (self, first, last):
        '''the constructor for a player'''
        self.first = first
        self.last = last
        self.rating = 0
        self.info = []


    def update(self, pos, team, year, att, yards, tds, fumbles ):
        '''create a list of information for this player for this year and 
        append it to the info field. Then call calcrating.'''
        self.info = self.info.append(year, pos, team, att, yards, tds, fumbles)

在程序中,我使用以下代码调用类的update函数:

^{pr2}$

playerDict和{}都已经定义好了,不用担心。但是,每当我试图运行程序并更新playerName,它会给我AttributeError: 'list' object has no attribute 'info'

在Python的网站指南中,它的构造函数中的空列表代码和更新代码正是我的代码,但是我的代码不起作用。有没有办法绕过这个错误?在


Tags: the代码posselfinfoforobjectdef
1条回答
网友
1楼 · 发布于 2024-05-16 08:51:53

您没有实例化Player类。因此,当您调用update时,实例self不会自动作为参数传递给update方法,因此其中一个参数(列表)将取代它。在

这应该是有效的:

player = Player()  # first instantiate
player.update(...)  # then do your stuff

注意:AFAIK,这只在python3中发生。在python2.x中,self有一个类型检查。在

顺便说一下,这条线也不行。在

^{pr2}$

检查^{}文档。在

相关问题 更多 >