sinat_35318364
2020-06-07 07:51
采纳率: 100%
浏览 333

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

问题如题

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条回答 默认 最新

  • threenewbee 2020-06-07 09:21
    已采纳

    我这里测试,food是可以被更新的啊。

    #!/usr/bin/python
    import random
    
    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
            print(self.food)
    ev = Environment()
    ev.clock_tick()
    print(ev.food)
    
    

    Food at {(2, 7), (6, 4), (0, 6), (6, 7), (3, 5)}
    Food disappears at (0, 6)
    {(6, 7), (3, 5), (6, 4), (2, 7)}
    {(6, 7), (3, 5), (6, 4), (2, 7)}

    打赏 评论

相关推荐 更多相似问题