假设我的课程Game
包含属性player1
,player2
和Q
。 player1
和player2
本身就是类Player
的实例,它还有一个名为Q
的属性。我想这样做,当我实例化一个Game
时,它与它Q
的实例共享它的Player
。
为了说明我的意思,请考虑以下代码:
class Game:
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
self.Q = {}
class Player:
def __init__(self, mark):
self.mark = mark
self.Q = {}
player1 = Player(mark="X")
player2 = Player(mark="O")
game = Game(player1, player2) # Instantiate a game with player 1 and player 2
game.Q["some key"] = "some value"
# I would like this to happen automatically
player1.Q = game.Q
player2.Q = game.Q
我喜欢player1
和player2
Q
变量,只要它发生变化,就会自动更新为game.Q
。我怎样才能做到这一点?