简体   繁体   中英

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

Brand new to Python (and coding altogether). Just stepping into Object-Oriented Programming and this is the first Class I've defined, and I'm having an issue with one of the functions. The line "total += coin.value" is giving me:

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

So I take it my value function is wrong, but I'm not really sure what the problem is...

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(),

value is the name of both a method and a field on a Coin class.

Just rename the method value to get_value and replace:

total += coin.value

with:

total += coin.get_value()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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