简体   繁体   English

打印类实例列表的随机实例,但得到RecursionError python3

[英]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. __str__方法默认情况下会调用__repr__ ,而您通过调用self上的str函数来覆盖__repr__方法来调用__str__方法,则在尝试打印cards对象时会导致无限递归。

You should make the __str__ method return a reasonably readable representation of the cards object instead: 您应该使__str__方法返回cards对象的合理可读的表示形式:

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

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

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