一个类方法可以改变另一个类中的变量作为不可预见的副作用吗?

2024-09-30 06:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我对两门课有些意见。这是我在主循环中写的

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不应该更改

我真的很抱歉,如果代码看起来混乱,我试图只包括相关的部分


Tags: 方法self列表defprintballsetposplayer2
2条回答

代码中的两个变量似乎链接到同一个列表,因此更改其中一个变量将更改另一个变量

你没有做过类似ball.posSize = player1.posSize的事情吗

如果是,则创建了对同一列表的第二个引用

要解决此问题,请将ball.posSize = player1.posSize更改为ball.posSize = player1.posSize[:]

任何mutable对象(如list)都可以被任何有权访问它的对象更改。例如,如果您的getPosSize()方法返回list本身,那么您可以进行影响相同列表的更改

class One(object):
    CLS_LST = [1, 2, 3]
    def __init__(self):
        self.lst = [4, 5, 6]

    def get_cls_pos(self):
        return One.CLS_LST

    def get_pos(self):
        return self.lst

class Two:
    def do_smthng(self, data):
        data.append(-1)



a = One()

print('This is One.CLS_LST: {}'.format(a.CLS_LST))
print('This is a.lst: {}'.format(a.lst))
b = Two()
print('Calling b do something with One.CLS_LST')
b.do_smthng(a.get_cls_pos())
print('This is One.CLS_LST: {}'.format(a.CLS_LST))
print('Calling b to do something with a.lst')
b.do_smthng(a.get_pos())
print('This is a.lst: {}'.format(a.lst))

此代码的结果将打印:

This is One.CLS_LST: [1, 2, 3]
This is a.lst: [4, 5, 6]
Calling b to do something with One.CLS_LST
This is One.CLS_LST: [1, 2, 3, -1]
Calling b to do something with a.lst
This is a.lst: [4, 5, 6, -1]

如果确实要传递列表的副本,请尝试使用return list[:]

相关问题 更多 >

    热门问题