首页 > 解决方案 > 在 Python 类中共享变量的正确方法

问题描述

我正在尝试使用 Python 为游戏开发 AI。因此,我有一个“游戏”类和一个“AI”类。

我想在 AI 中使用游戏变量(例如游戏板),但我不确定最好的方法是什么。现在,我发现将信息从游戏传递给 AI 的唯一方法是每次都将其作为参数。我觉得有一种更好的方法可以与 AI 共享变量,而无需每次都进行争论。

我会做一些类似的事情(我知道这段代码不能工作,但仍然):

class Game():
    def __init__(self):
        self.board = 1 #It will be an array
        self.ai = AI(self.board)

    def functionThatUpdateTheBoard(self):
        self.board = 2

    def useTheAI(self):
        print(self.board)
        self.ai.getAction()

class AI():
    def __init__(self,board):
        self.board = board
        print(self.board)
    def getAction(self):
        print(self.board)

game = Game()
game.functionThatUpdateTheBoard()
game.useTheAI()

并得到:

1
2
2

谢谢您的帮助 :)

标签: pythonclass

解决方案


看看你是否可以使用观察者模式。

例如,当“板”在 Game 类中更改值时创建订阅者并调用。如果一个类需要“板”的更新值,他们可以订阅,这会在“板”值更改时触发。

通过这种方式,您可以非常确定正在更改的值,而与所使用的数据类型的不变性无关。

class Game(object):
 def __init__(self):
    self.board = 1
    self.observers = []

 def functionThatUpdateTheBoard(self, new_value): 
    # you can change this to setter ,
    # refer https://www.tutorialspoint.com/What-are-Getters-Setters-methods-for-Python-Class
    self.board = new_value
    for fn in self.observers:
        fn(self.board) # send your board value here.


 def subscribe(self, callback):
    self.observers.append(callback)

class AI(object):
  def game_board_value_changed(self, value):
      print("Printing value in AI class")
      print("Value of 'board' changed in Game class to {}".format(value))


game = Game()
ai = AI()
game.subscribe(ai.game_board_value_changed)
print("*"*50)
modified_value = 10
print("Board value changed in Main to {}".format(modified_value))
game.functionThatUpdateTheBoard(modified_value)
print("*"*50)
modified_value = 100
print("Board value changed in Main to {}".format(modified_value))
game.functionThatUpdateTheBoard(modified_value)
print("*"*50)

**************************************************
Board value changed in Main to 10
Printing value in AI class
Value of 'board' changed in Game class to 10
**************************************************
Board value changed in Main to 100
Printing value in AI class
Value of 'board' changed in Game class to 100
**************************************************

推荐阅读