找回密码
 立即注册

扫一扫,访问微社区

QQ登录

只需一步,快速开始

查看: 2346|回复: 2

[求助] 求助,两个实例,修改其中一个另一个也会变化

1

主题

1

帖子

1

积分

贫民

积分
1
toucha3 发表于 2017-8-9 12:40:47 | 显示全部楼层 |阅读模式
我在写个小游戏的时候碰到了问题,请大侠帮忙看看。
Game类如果用第一个__init__方法执行,如果修改g1的cells[0],g2也发生变化
如果用第二个__init__方法执行就没事,不知道问题出在哪

class Cell:
    pos=(9, 9)
    value=-1
    def __init__(self, value, pos):
        self.value, self.pos = value, pos
    def __lt__(self, cell):
        if self.value<cell.value:   return True
        return True if self.value==cell.value and self.pos<cell.pos else False

class Game:
    cells=[]
    step=-1
    father=None
    #### 1
    def __init__(self, ti='001021043100122133233301321343'):
        self.cells.clear()
        cellCount=int(len(ti)/3)
        for i in range(cellCount):
            self.cells.append(Cell(int(ti[i*3+2]), (int(ti[i*3]), int(ti[i*3+1]))))
    #### 2
    def __init__(self, ti='001021043100122133233301321343'):
        self.cells.clear()
        cellCount=int(len(ti)/3)
        self.cells=[ Cell(int(ti[i*3+2]), (int(ti[i*3]), int(ti[i*3+1]))) for i in range(int(len(ti)/3)) ]
        self.cells.sort()

g1=Game()
g2=Game()

回复

使用道具 举报

0

主题

1

帖子

1

积分

贫民

积分
1
youfl 发表于 2017-8-9 17:32:42 | 显示全部楼层
你的cells是类属性,而且是list,这个是浅拷贝的,所以修改了个g1的cells肯定也会修改g2的cells
回复 支持 反对

使用道具 举报

1

主题

14

帖子

14

积分

贫民

积分
14
lywane 发表于 2017-8-14 09:59:47 | 显示全部楼层
关键在于append方法是修改内存中的数据,而=是修改变量的指向
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表