简体   繁体   中英

Printing a random instance of a list of class instances but getting a RecursionError python3

import random

class cards():

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

    def __repr__(self):
       return str(self)

deck = []
card_val = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
card_suit = ['♦','♥','♠','♣']

for x in card_val:
    for y in card_suit:
        card = cards(x,y)
        deck.append(card)

print(random.choice(deck))

When it tries to print it gets the following error:

RecursionError: maximum recursion depth exceeded while calling a Python object

I'm very new with class instances. I looked around and couldn't find any answers that worked. Any help would be appreciated.

The __str__ method calls the __repr__ by default, and you've overridden the __repr__ method to call the __str__ method by calling the str function on self , resulting in an infinite recursion when you try to print a cards object.

You should make the __str__ method return a reasonably readable representation of the cards object instead:

def __str__(self):
   return self.val + self.suit

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