在python类的__str__函数内调用方法

时间:2017-12-09 00:34:33

标签: python function class methods

'List' object has no attribute 'points'是我得到的错误。我想我没有在points函数内正确调用__str__,但不知道如何修复它。之前,我在points之前定义了__str__并且遇到了同样的错误。

class Persons(object):

    def __init__(self,name,radius,home_universe,x,y,dx,dy,current_universe,rewards):

        self.name = name
        self.radius = radius
        self.home_universe = home_universe
        self.x = x
        self.y = y
        self.dx = dx
        self.dy = dy
        self.current_universe = current_universe
        self.rewards = rewards

    def __str__(self):

        return '{} of {} in universe {}\n at ({},{}) speed ({},{}) with {} rewards and {} points'.\
               format(self.name, self.home_universe, self.current_universe, self.x, self.y, self.dx,\
                      self.dy, len(self.rewards), self.rewards.points())

    def points(self):

        cnt = 0
        if len(self.rewards) == 0:
            return 0
        else:
            for reward in self.rewards:
                cnt += reward[2] 
            return cnt 

1 个答案:

答案 0 :(得分:2)

您使用self.rewards.points(),但只有self.points()

使用self.points()

相关问题