如何在类中生成一个变量,以便它的所有方法都可以访问它?

2024-04-19 22:50:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让cards[]成为类的一个属性,这样当我创建__str__方法时,它就可以识别它了。现在它返回的是:

screenshot of error message

class Deck:

    def __init__(self):
        cards = []
        Ranks = ['A', '2', '3', '4','5','6','7','8','9', '10','K', 'Q', 'J']
        Suits = ['♣','♥','♦','♠']
        indexNum = 0
        for i in range(len(Suits)):
            for j in range(len(Ranks)):
                tempCard = PlayingCard(Suits[i],Ranks[j])
                cards+= [tempCard]

                print(cards[indexNum])
                indexNum+=1

    def __str__(self):
        stringOfCards = ''
        x = 1
        while (x<len(cards)):
            myCard =  Deck.cards[x]
            print("this is i")
            print(myCard)
            stringOfCards+="'"+ myCard.rank +"'"+ 'of ' + myCard.suit+", "
            x+=1
        return stringOfCards

deck1 = Deck()
print(deck1)

Tags: inselfforlendefrangecardsprint
1条回答
网友
1楼 · 发布于 2024-04-19 22:50:00

__init__方法中的所有属性前面加上self.。你知道吗

同样,在Python中,在引用变量时使用小写(例如rank而不是Rank)和使用snake_case而不是camelCase是Python的。你知道吗

例如

class Deck:
    def __init__(self):
        self.cards = ["4H, 5S"]

    def __str__(self):
        return self.cards

然后可以通过创建一个Deck对象并引用cards变量来引用卡片。你知道吗

d = Deck()
d.cards
>> ["4H, "5S"]

相关问题 更多 >