python如何从其他类获取变量的访问权限

问题描述 投票:0回答:2

又是我。我想从方法deck中的class Deck中的class Table中访问变量howManyCards。换句话说,我创建了一个牌组,并且我想做一个方法,让我从牌组列表中取出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)
python class variables
2个回答
0
投票

正如MobileBen指出的那样,您没有访问Deck对象。


1
投票

您需要进行两项更改:

© www.soinside.com 2019 - 2024. All rights reserved.