簡體   English   中英

嘗試在 class 中初始化 class 時 Python 中的 AttributeError

[英]AttributeError in Python when attempting to initialize a class in a class

我試圖將 class 調用到類的初始化方法中,但我收到一個屬性錯誤。 有誰知道為什么會發生這種情況? 我可以用另一個 class 來做這件事,但它似乎不喜歡我制作的Movement() class。

Board() () 中的add_piece()方法似乎是導致問題的原因。

class Movement:
    """
    Class to help separate movements from the board methods
    """
    def __init__(self):
        pass

    def ind(self, pos):
        """
        Converts the string input to an easier index for the board
        """
        row = int(pos[1:]) - 1
        column = self.letter_to_column(pos)
        return row, column

    def letter_to_column(self, pos):
        """
        Method to convert string letters of columns to int to index
        """
        column_dict = {}
        column_dict['a'] = 0
        column_dict['b'] = 1
        column_dict['c'] = 2
        column_dict['d'] = 3
        column_dict['e'] = 4
        column_dict['f'] = 5
        column_dict['g'] = 6
        column_dict['h'] = 7
        column_dict['i'] = 8
        return column_dict[pos[0]]

# BOARD -------------------------------------------------------------------
class Board:
    """
    Represents the board and its pieces
    """
    def __init__(self):
        """
        Builds the board and places the pieces in its spots
        """
        self._board = []
        for i in range(10):
            self._board.append([None for i in range(9)])
        self.place_pieces()

        self._move = Movement()

    def add_piece(self, pos, piece):
        """
        pos is a string of a letter (column) and a number (row)
        for example pos = 'a2' which is the first column in the second row
        """
        self._board[self._move.ind(pos)[0]][self._move.ind(pos)[1]] = piece

該問題與Movement無關:它與Board中缺少的方法有關。 Board.place_pieces未定義,因此Board.__init__中的表達式self.place_pieces()將拋出AttributeError

順便說一句,如果Movement class 的唯一目的是收集相關的輔助函數,您可能需要考慮使用這些classmethodstaticmethod您可以在此處閱讀更多信息):

class Movement:
    COLUMNS = {
        letter: index
        for index, letter in enumerate("ABCDEFGH")
    }

    @classmethod
    def get_indices(cls, coordinate):  # cls is to class methods what self is to instance methods.
        # Rough validation of the coordinate:
        if not len(coordinate) == 2: 
            ...  # Raise some exception.

        # Assignment via sequence unpacking
        # See https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
        column, string_row = coordinate.upper()
 
        # Row should be representable as a digit and 
        # in a specific range.
        row_index = int(string_row)
        if row_index < 1 or row_index > 8:
            ... # Raise an exception.

        # If column isn't in ABCDEFGH, the dictionary
        # access here will throw (desirable).
        return row_index - 1, cls.COLUMNS[column]

Movement.COLUMNS是使用字典理解生成的class 變量 enumerate是一個內置的 function ,我們用它來返回字符串ABCDEFG中每個字母的索引。

然后,您可以跳過self._mode的創建並編寫:

row_index, column_index = Movement.get_indices("A2")

例如,在Board.add_piece中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM