为什么这些Python类变量会出现意外行为

时间:2015-03-06 01:59:00

标签: python python-3.x

Python新手在这里。我使用类变量home_teamaway_team遇到了一些意想不到的行为(见下文)。

class GameTeam():

    def __init__(self, prev_game=None, prev_result=None, wins=0, losses=0):
        self.prev_game = prev_game
        self.prev_result = prev_result
        self.wins = wins
        self.losses = losses

class Game1():
    home_team = GameTeam()
    away_team = GameTeam()

    def __init__(self, game_num):
        self.game_num = game_num

    def __str__(self):
        return str(self.game_num)

    def __repr__(self):
       return str(self)

game11 = Game1(1)
game12 = Game1(2)

game11.away_team.losses = game11.away_team.losses + 1
game12.away_team.losses = game12.away_team.losses + 1

print(game11.away_team.losses) #Result is 2
print(game12.away_team.losses) #Result is 2

但是,如果我在home_team方法中初始化away_team__init__(),我会得到预期的结果

class GameTeam():

    def __init__(self, prev_game=None, prev_result=None, wins=0, losses=0):
        self.prev_game = prev_game
        self.prev_result = prev_result
        self.wins = wins
        self.losses = losses

class Game2():

    def __init__(self, game_num):
        self.game_num = game_num
        self.home_team = GameTeam()
        self.away_team = GameTeam()

    def __str__(self):
        return str(self.game_num)

    def __repr__(self):
       return str(self)

game21 = Game2(1)
game22 = Game2(2)

game21.away_team.losses = game21.away_team.losses + 1
game22.away_team.losses = game22.away_team.losses + 1

print(game21.away_team.losses) #Returns 1
print(game22.away_team.losses) #Returns 1

有人可以向我解释这里发生了什么,或者指向我解释这个问题的文档部分吗?

1 个答案:

答案 0 :(得分:1)

类变量与实例变量:

https://docs.python.org/3.4/tutorial/classes.html#class-and-instance-variables

类变量在类的所有实例中共享。实例变量是每个实例。