TypeError:+ =不支持的操作数类型:'method'和'int'(Python) [英] TypeError: unsupported operand type(s) for +=: 'method' and 'int' (Python)
问题描述
我正在控制台中制作一个小型游戏,历时数天。游戏首先将矿工的矿石和金钱金额初始化为0。当他进行开采时,我的函数会选择一个介于20到71之间的随机整数,然后将其奖励为矿石。我正在尝试将已开采的矿石分配给玩家的矿石量。我遇到一个经常发生的错误,指出+ =是方法和整数的不受支持的操作数。完整的代码和跟踪信息如下。
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.
代码
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
的引用方法,并且不能将其递增一个数字(即使可以,也不会执行您想要的操作)。
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).
您应该更改
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
和其他方法类似。
这篇关于TypeError:+ =不支持的操作数类型:'method'和'int'(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!