使用空字典 and/or 列表创建 class 实例的正确方法是什么?

What is the proper way to create a class instance with an empty dictionary and/or list?

表明我正在以正确的方式创建我的空字典。

class Board:
    def __init(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()

我创建了一个 class

的实例
b = Board()

但是当我去调用它时...

b.playCard(1, cardPic)

我收到错误:

AttributeError: 'Board' object has no attribute 'lastCardsPlayedDict'

第一种方法需要__init__而不是__init:

class Board:
    def __init__(self): #notice the change here
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()

愚蠢的错误...您的 init 方法定义不正确。

这是更正后的代码。

class Board:
    def __init__(self):
        self.pot = 0
        self.activePlayer = 1
        self.activePlayers = 4
        self.passedPlayers = 0
        self.firstHand = True
        self.lastCardsPlayedList = []
        self.lastCardsPlayedDict = {}

    def playCard(self, cardInt, cardPic):
        self.lastCardsPlayedDict[cardInt] = cardPic
        self.lastCardsPlayedList.append(cardInt)
        self.lastCardsPlayedList.sort()


b = Board()
b.playCard(1, 'cardPic')

print(b)