简体   繁体   中英

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. I have tried to use __str__ and __repr__ respectively but maybe I am unfamiliar with how these work exactly.

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.

it seems that you have forgotten to define the __repr__ method for the Card class. Should be something like:

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

whereas for the Deck I would define it as:

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

the resulting output will be 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:
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}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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