sinat_35318364
sinat_35318364
2020-06-07 07:51

Python中如何更新Class类中的自定义变量

30
  • python

问题如题

class Environment():

    grid_end = 9         
    grid_size = grid_end + 1
    init_food = 5           
    food_del_chance = 0.05 
    food_add_chance = 0.20

    def __init__(self):
        self.food = set()
        for i in range(self.init_food):
            X = random.randint(0, self.grid_end)
            Y = random.randint(0, self.grid_end)
            if not ((X,Y) in self.food):
                self.food.add((X,Y))
        print("Food at", end=" ")
        print(self.food)


    def clock_tick(self):
    # possibly delete food items -- copy elements not deleted into new set
        food_set = set()
        for location in self.food:
            r = random.random()
            if (r > self.food_del_chance):
                food_set.add(location)
            else:
                print("Food disappears at", end=" ")
                print(location)
        #print(food_set)
        self.food = food_set

在Class中的def clock-tick中,把food-set赋值给了self.food,但是self.food并没有更新,还是保持原来的set()。请问如何修改才能让self.food更新?
完整程序连接:https://pan.baidu.com/s/1jpYoqm4eKk5vOvIgYtJDjw
密码:llgj

也许并不是在class Environment()中没更新,可能在class agent中读取时一直读取的是原来的数据。头大。

终于发现问题了,问题存在于class agent中,集合更新使用了self.food-seen.update(percepts)。update会添加新元素进入set(),但是对于消失的元素不会进行删除。

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答