繁体   English   中英

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

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

全新的Python(以及全部编码)。 刚刚进入面向对象编程,这是我定义的第一个类,而我对其中一个函数有疑问。 “ total + = 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(),

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

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

total += coin.value

有:

total += coin.get_value()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM