• Python中如何更新Class类中的自定义变量
  • 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更新?


  • vicky    2020-06-08 10:53:20
  • 阅读 1482    收藏 0    回答 1
  • 邀请
  • 收藏
  • 分享
发送
登录 后发表评论
  • 51testing软件测试圈微信