TypeError:+=:'int'和'instancemethod'不支持的操作数类型

2024-04-26 21:05:12 发布

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

全新的Python(和代码)。刚进入面向对象编程,这是我定义的第一个类,我对其中一个函数有问题。“total+=coin.value”一行告诉我:

TypeError: unsupported operand type(s) for +=: 'int' and 'instancemethod'

所以我认为我的价值函数是错误的,但我不确定问题是什么。。。

import random

class Coin:
    def __init__(self, coinValue=1):
        if coinValue == 1:
            self.coin = "Penny"
        elif coinValue == 5:
            self.coin = "Nickel"
        elif coinValue == 10:
            self.coin = "Dime"
        elif coinValue == 25:
            self.coin = "Quarter"
        elif coinValue == 100:
            self.coin = "Loonie"
        else:
            self.coin = "Toonie"

    def __str__(self):
        return self.coin

    def value(self):
        self.value = 0
        if self == "Penny":
            self.value = 1
        elif self == "Nickel":
            self.value = 5
        elif self == "Dime":
            self.value = 10
        elif self == "Quarter":
            self.value = 25
        elif self == "Loonie":
            self.value = 100
        else:
            self.value = 200
        return self.value

    def flip(self):
        side = random.randint(1,2)
        if side == 1:
            return "Heads"
        else:
            return "Tails"


if __name__ == '__main__':
    coin = Coin()
    print 'Your first coin is a %s.' % (coin)
    purse = [coin]
    print 'Adding four more coins to your purse...'
    for i in range(4):
        coin = Coin(random.choice([1,5,10,25,100,200]))
        purse.append(coin)
    print 'In your purse you now have:'
    for coin in purse:
        print '\ta', coin
    total = 0
    for coin in purse:
        total += coin.value
    print 'The total value of the coins in your purse is', total, 'cents.'

    print 'Flipping your coins you get:',
    for coin in purse:
        print coin.flip(),

Tags: inselfforyourreturnifvaluedef