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

时间:2014-03-16 03:21:29

标签: python python-2.7

全新的Python(并完全编码)。刚刚进入面向对象的编程,这是我定义的第一个类,并且我遇到了其中一个函数的问题。该行"总计+ = coin.value"给我的是:

  

TypeError:+ =的不支持的操作数类型:' int'和' 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(),

1 个答案:

答案 0 :(得分:5)

valueCoin类的方法和字段的名称。

只需将方法value重命名为get_value并替换:

total += coin.value

使用:

total += coin.get_value()