Search code examples
pythonclassmethodsintoperands

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


I am making a small game in the console that takes place over several days. The game starts by initializing the miners ore and money amounts as 0. When he mines, my function chooses a random integer between 20 and 71 that will then award him that amount in 'ore'. I am trying to assign the ore that has been mined to my player's ore amount. I am having a reoccurring error that states that += is an unsupported operand for method and int. Full code and trace is below.

Code

import pyautogui as pag
import time
import sys
import random


class Miner:
    def __init__(self, oreDeposit, moneyDeposit):
        self.oreAmount = oreDeposit
        self.moneyAmount = moneyDeposit

    def oreDeposit(self, oreAmount):
        self.oreDeposit += oreAmount

    def oreWithdraw(self, oreAmount):
        self.oreWithdraw -= oreAmount
# -------------end of ore

    def moneyDeposit(self, moneyAmount):
        self.moneyDeposit += moneyAmount

    def moneyWithdraw(self, moneyAmount):
        self.moneyWithdraw -= moneyAmount
# -------------end of money

    def oreBalance(self):
        return self.oreAmount

    def moneyBalance(self):
        return self.moneyAmount
# -------------end of balances

def miningAction():
    x = random.randint(20, 71)
    for i in range(x):
        time.sleep(0.1)
        print(i)
        oreRecovered = i
        player.oreDeposit(oreRecovered)

player = Miner(0, 0)
miningAction()
print (player.oreAmount)

Full traceback

0
Traceback (most recent call last):
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 41, in <module>
    miningAction()
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 38, in miningAction
    player.oreDeposit(oreRecovered)
  File "C:/Users/####/PycharmProjects/BoardGame/mine.py", line 12, in oreDeposit
    self.oreDeposit += oreAmount
TypeError: unsupported operand type(s) for +=: 'method' and 'int'

Process finished with exit code 1

Solution

  • self.moneyDeposit is a reference to the moneyDeposit method and it cannot be incremented by a number (and even if it could, it wouldn't do what you want it to do).

    You should change

    def moneyDeposit(self, moneyAmount):
        self.moneyDeposit += moneyAmount
    
    def moneyWithdraw(self, moneyAmount):
        self.moneyWithdraw -= moneyAmount
    

    into

    def moneyDeposit(self, moneyAmount):
        self.moneyAmount += moneyAmount
    
    def moneyWithdraw(self, moneyAmount):
        self.moneyAmount -= moneyAmount
    

    and similarly for the other methods.