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

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

我正在控制台中制作一个持续数天的小游戏。游戏首先将矿工的矿石和金钱数量初始化为 0。当他开采时,我的函数会选择 20 到 71 之间的随机整数,然后在 'ore' 中奖励他该数量。我正在尝试将已开采的矿石分配给我的玩家的矿石数量。我有一个反复出现的错误,表明 += 是方法和 int 不受支持的操作数。完整代码和跟踪如下。

代码

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)

完整追溯

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

self.moneyDeposit 是对 moneyDeposit 方法的引用,它不能增加一个数字(即使可以,它也不会做你想做的事)。

你应该改变

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

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

进入

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

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

其他方法也类似。