我对两门课有些意见。这是我在主循环中写的
print(player1.getPosSize())
ball.setPos(windowWidth, [player1.getPosSize(), player2.getPosSize()],
[player1.getSpeed(), player2.getSpeed()])
print(player1.getPosSize())
如果有帮助的话,这里有一些方法定义
(球类)
def setPos(self, windowWidth, playerPosSizes, playerSpeed):
playerPosSizes[0].append(playerSpeed[0])
playerPosSizes[1].append(playerSpeed[1])
playerPosSizeSp = playerPosSizes
(玩家类)
def getPosSize(self):
return self.posSize
def getSpeed(self):
return self.ysp
这是输出:
[80, 285.0, 40, 150]
[80, 285.0, 40, 150, 0.0]
因此getPosSize()
返回的列表被更改。这很奇怪,因为getPosSize
返回一个只存在于player类中的列表posSize
。我在另一个类的方法中使用了posSize
的值。我不明白posSize
列表是如何改变的!我的意思是当我打电话给getPosSize
时,我会得到一份posSize
的副本,对吗?因此,当我在ball类的方法setPos
中使用该副本时,原始的posSize
不应该更改
我真的很抱歉,如果代码看起来混乱,我试图只包括相关的部分
代码中的两个变量似乎链接到同一个列表,因此更改其中一个变量将更改另一个变量
你没有做过类似
ball.posSize = player1.posSize
的事情吗如果是,则创建了对同一列表的第二个引用
要解决此问题,请将
ball.posSize = player1.posSize
更改为ball.posSize = player1.posSize[:]
任何
mutable
对象(如list
)都可以被任何有权访问它的对象更改。例如,如果您的getPosSize()
方法返回list
本身,那么您可以进行影响相同列表的更改此代码的结果将打印:
如果确实要传递列表的副本,请尝试使用
return list[:]
相关问题 更多 >
编程相关推荐