简体   繁体   English

为什么我的代码返回变量的地址而不是值?

[英]Why is my code returning the address of the variable instead of the value?

I am finding it difficult to understand why my code is returning my memory address.我发现很难理解为什么我的代码返回我的 memory 地址。 I have tried to use __str__ and __repr__ respectively but maybe I am unfamiliar with how these work exactly.我曾尝试分别使用__str____repr__但也许我不熟悉它们的工作原理。

import random

class Card:
    def __init__(self, suit, value):
        self.suit = suit #['H','D','C','S']
        self.value = value #['A',2,3,4,5,6,7,8,9,10,'J','Q','K']
    
class Deck:
    def __init__(self):
        self.cards =[]
    
    def __repr__(self):
        return f'Card("{self.card}")'
    
    def build(self):
        for x in['H','D','C','S']:
            for y in range(1,14):
                self.cards.append(Card(x,y))
                if(y==1):
                    self.cards.append(Card(x,'A'))
                elif(y==11):
                    self.cards.append(Card(x,'J'))
                elif(y==12):
                    self.cards.append(Card(x,'Q'))
                elif(y==13):
                    self.cards.append(Card(x,'K'))
    def shuffle(self):
        for i in range(len(self.cards)-1,0,-1):
            r = random.randint(0,i)
            self.cards[i], self.cards[r]= self.cards[r], self.cards[i]
                
    def deal(self):
        card = self.cards.pop()
        print(repr(card))

d = Deck()
d.build()
d.shuffle()
d.deal()
<__main__.Card object at 0x7f836e0ed070>

Above is the Code and the output that I am getting, any help would be really appreciated.以上是我收到的代码和 output,如有任何帮助,我们将不胜感激。

it seems that you have forgotten to define the __repr__ method for the Card class. Should be something like:您似乎忘记了为Card class 定义__repr__方法。应该是这样的:

    def __repr__(self):
        return f"Card({self.value})"

whereas for the Deck I would define it as:而对于 Deck,我会将其定义为:

    def __repr__(self):
        return f'Deck("{self.cards}")'

the resulting output will be Card(<some-number>) .结果 output 将是Card(<some-number>)

Your Class Card needs the __repr__ function, as python tries to print an Instance of the Type Card, not the deck:您的 Class Card需要__repr__ function,因为 python 试图打印 Type Card 的实例,而不是卡片组:

class Card:
def __init__(self, suit, value):
    self.suit = suit  # ['H','D','C','S']
    self.value = value  # ['A',2,3,4,5,6,7,8,9,10,'J','Q','K']
def __repr__(self):
    return f'{self.suit}-{self.value}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM