首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >set在python类中的行为异常

set在python类中的行为异常
EN

Stack Overflow用户
提问于 2015-04-23 21:23:21
回答 1查看 72关注 0票数 1

我有一些对象,比如画布上的矩形,对于每个对象,我希望有一个set,其中包含其相邻单元格的id。

下面是类的代码,idC是我感兴趣的in,它们由Tkinter的create_rectangle函数分配给每个单元格

代码语言:javascript
复制
class Cell(Rectangle):
    def __init__(self, canvas, row, column):
        # make a 10x10 rectangle in the given row, column
        x0 = column * 10
        y0 = row * 10
        x1 = x0 + 10
        y1 = y0 + 10         

        super(Cell, self).__init__(canvas, (x0, y0, x1, y1), "white")

        self.get_neighbours()


    state = 'dead'
    neighbours = set()
    border = set()

    def get_neighbours(self):

        if self.idC % 95 == 1: self.border.add('left')  #the numbers are like so because my canvas is 950x950
        if self.idC % 95 == 0: self.border.add('right')
        if self.idC < 96: self.border.add('top')
        if self.idC > 8930: self.border.add('bottom')
        if 'left' not in self.border: self.neighbours.add(self.idC - 1)
        if 'right' not in self.border:self.neighbours.add(self.idC + 1)
        if 'top' not in self.border:
            if 'left' not in self.border:self.neighbours.add(self.idC - 94)
            self.neighbours.add(self.idC - 95)
            if 'right' not in self.border:self.neighbours.add(self.idC - 96)
        if 'bottom' not in self.border:
            if 'left' not in self.border:self.neighbours.add(self.idC + 94)
            self.neighbours.add(self.idC + 95)
            if 'right' not in self.border:self.neighbours.add(self.idC + 96)

    def change_state(self):
        self.state = 'alive' if self.state == 'dead' else 'dead'
        color = "black" if self.state == "alive" else "white"
        print(self.idC)
        print("neighbours:")
        #print(self.neighbours)
        print(len(self.neighbours))
        if not GameOfLife.running: self.canvas.itemconfigure(self.idC, fill=color) 

下面是我如何使用其他小部件在另一个类中创建所有单元格:

代码语言:javascript
复制
    for i in range(95):
        for p in range(95):
            self.organism.append(Cell(c, i, p))

    for cell in self.organism:            
        c.tag_bind(cell.idC, '<ButtonPress-1>', lambda _, x = cell: x.change_state())

发生的情况是,除了触发该函数的id之外,所有的id都被添加到设置的neighbours中;此外,其他一切都可以正常工作--单击单元格可以正确地打印出它的id

一定是新手弄错了,但我不知道出了什么问题。

更新:我发现每个单元格都被标记为在画布上的所有边框上,所以当函数一次又一次被调用时,它一定会将所有ids添加到同一集合中,而不是为类的每个实例创建不同的集合。我试着从不同的地方调用它,但我仍然得到相同的结果...

EN

回答 1

Stack Overflow用户

发布于 2015-04-24 02:52:27

好了,我把整个get_neighbours()和所有与之相关的变量都移到了父类中,现在它可以正常工作了

我还是不知道它为什么会这样

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29824820

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档