如何在Python中的不同类之间共享实例变量

时间:2016-08-15 09:10:08

标签: python

假设我的课程Game包含属性player1player2Qplayer1player2本身就是类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

我喜欢player1player2 Q变量,只要它发生变化,就会自动更新为game.Q。我怎样才能做到这一点?

0 个答案:

没有答案