尝试将实例变量映射到类中的字典

2024-05-15 11:34:52 发布

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

这是个新手,正在学习Python

我试图创建一个类,以便在实例化该类的实例时,将用户输入的参数映射到一个类字典,并从字典中获取值并存储在实例变量中,而不是用户指定的参数中这是我的代码:

class Card(object):
    '''This class sets up a playing card'''
    
    suits = {'d':'diamonds', 'h':'hearts', 's':'spades', 'c':'clubs'}
    values = {1:'Ace',2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King'}
    
    def __init__ (self, value, suit):
        self.value = value
        self.suit = suit
        
    def get_value(self):
        return values[self.value]
    
    def get_suit(self):
        return self.suit
    
    def __str__(self):
        my_card = str(self.value) + ' of ' + str(self.suit)
        return my_card

因此,如果我要键入:

my_card = Card (1,'d')

然后,调用我创建的get_value方法,它将返回“Ace”

如果我调用get_suit方法,它将返回“diamonds”

如果我打印my_card,它会打印:钻石王牌

有人知道怎么做吗


Tags: 实例用户self参数getreturn字典value
2条回答

老实说,你得到了你需要的一切。。。只需要以正确的方式将各个部分组合在一起

class Card():
    def __init__ (self, value, suit):
            self.value = value
            self.suit = suit
            self.suits = {'d':'diamonds', 'h':'hearts', 's':'spades', 'c':'clubs'}
            self.values = {1:'Ace',2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King'}

    def __str__(self):
            my_card = '{} of {}'.format(self.values[self.value], self.suits[self.suit])
            return my_card
my_card = Card(1, 'd')
print(my_card)

你已经非常非常接近你所拥有的

由于valuessuits是Card类的属性,因此需要使用相同的self.符号来访问它们

因此,您的卡片类将如下所示(我更改的行上方的注释):

class Card(object): 
    '''This class sets up a playing card'''
    suits = {'d':'diamonds', 'h':'hearts', 's':'spades', 'c':'clubs'}
    values = {1:'Ace',2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9, 10:10, 11:'Jack', 12:'Queen', 13:'King'}

    def __init__ (self, value, suit):
        self.value = value
        self.suit = suit

    def get_value(self):
        # Access the values dictionary with self.values
        return self.values[self.value]

    def get_suit(self):
        # Same thing for suits!
        return self.suits[self.suit]

    def __str__(self):
        # Changed the accessor for suits to be complete
        my_card = str(self.value) + ' of ' + str(self.suits[self.suit])
        return my_card

或者,对于您的__str__,您可以

def __str__(self):
    return self.get_value() + ' of ' + self.get_suit()

相关问题 更多 >