python 如何从其他类访问变量

标签 python class variables

又是我。我想在方法 howManyCardsclass Table 中从 class Deck 访问变量 deck。换句话说,我创建了一副牌,我想做一个方法,让我从牌组列表中取出num第一张牌,但我不知道如何正确编写它。行 self.onTheTable = Deck.deck[:num] 不起作用。我有一个错误 AttributeError: type object 'Deck' has no attribute 'deck' 我理解,但我不知道如何以正确的方式更改它。谢谢。

class Card:
    def __init__(self, figure, colour):
        self.colour = colour
        self.figure = figure
    def __repr__(self):
        return str(self.figure) + str(self.colour)

class Deck:
    def __init__(self):
        self.deck = []
    def createDeck(self):
        for colour in ["h", "d", "c", "s"]:
            for figure in ["2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K", "A"]:
                self.deck.append(Card(figure, colour))

class Table():
    def __init__(self):
        self.onTheTable = []
    def howManyCards(self, num):
       self.onTheTable = Deck.deck[:num]

deck = Deck()
deck.createDeck()
table = Table()
table.howManyCards(10)

最佳答案

您需要进行两项更改:

def howManyCards(self, deck, num):
   self.onTheTable = deck.deck[:num]

table.howManyCards(deck, 10)

原始代码 (Deck.deck[:num]) 的问题在于您将 deck 视为类变量。 deck 是一个实例变量。

关于python 如何从其他类访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150344/

相关文章:

python - 计算 Python 中元组中每个值的出现次数

html - 如何减少 Bootstrap 网格系统的代码?

variables - 在 MATLAB 中使用 sprintf 显示变量的小数

mysql - 在 MySql 中创建触发器时声明变量

bash - 根据多个值检查 bash 变量

python - 在 tkinter 中运行 matplotlib

安装了Python3.5但pip3指向python3.6

class - 在 Excel VBA 中使用类处理多个范围

jquery - 使用 jQuery 访问具有多个类的元素

python - 二维日期时间分组依据