Python错误地引用对象内部对象

时间:2016-11-30 06:35:51

标签: python

我有2个python类:Player和Board。该板包含一个带有" A1"空间的参考样式。

player.py的玩家类:

from board import Board

class Player:
    def __init__(self):
        self.name = input("Name: ")
        self.board = Board(3, ["A", "B", "C"])

board.py的董事会成员:

class Board:
    EMPTY = "0"
    spaces = {}
    def __init__(self, size, letters):
        for let in letters:
            for num in range(1, size + 1):
                self.spaces["{}{}".format(let, num)] = self.EMPTY

    def place_piece(self, spot):
        self.spaces[spot] = "X"

    def display_board(self):
        for let in letters:
            for num in range(1, size + 1):
                print("\n" + self.spaces["{}{}".format(let, num)]

当实例化Player时,它会在里面创建一个Board对象。 创建了2个玩家,每个玩家都被添加到列表玩家[]中。每个玩家的回合都选择一个名为current_player的简单1/0变量。

    from player import *
    from board import *

    current_player = 1
    players = []
    player_1 = Player()
    player_2 = Player()
    players.append(player_1)
    players.append(player_2)

    while True:
        # Switches players
        current_player = abs(current_player - 1)

        # Prints the current player's name
        print(players[current_player].name)

        # Calls some method which should alter the current player's board
        players[current_player].board.place_piece(input("> "))

        # Calls some method which should show the current player's board
        players[current_player].board.show_board()
显然,非常简化。该名称每次都打印正确。然而,董事会仅为两位球员使用第一个球员牌。我知道它的工作是因为球员'名称打印正确。

即使单独创建并放置在自己的列表中,问题仍然存在。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

正如现在所写,所发布的代码不应该正常工作。董事会中的两种方法place_piecedisplay_board需要接受“自我”和“自我”。作为第一个论点。

假设这是一个错字,那就是发生了什么。使用类成员 spaces创建类Board。每次在对象中引用self.spaces时,在对象中找不到它而是在类中查找。含义您对类Board的所有对象使用相同的dict。相反,要创建一个常规成员,请将声明放在init方法中,就像在Player类中一样:

class Board:
    EMPTY = "0"
    # Remove spaces = {}

    def __init__(self, size, letters):
        self.spaces = {}
        ...

最后,由于您使用的是Python 2x,请鼓励您始终使用新的样式类(即写class Board(object))。见What is the difference between old style and new style classes in Python?