如何正确实施/重载"__repr__"? [英] How to properly implement/overload "__repr__ "?

查看:155
本文介绍了如何正确实施/重载"__repr__"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python的新手,这可能是一个愚蠢的问题,但是如何正确实现 repr 方法?

New to python and this might be a silly question, but how does one properly implement the repr method?

我写了一个快速的小程序来模拟纸牌游戏,但是我不知道为 repr 方法写什么. Card类 repr 方法非常简单,但我不知道 DeckOfCards类的处理方法,这是我的代码:

I wrote a quick little program to simulate a game of cards but I don't know what to write for the repr method. The repr method for the Card class was pretty straight forward, but I don't know what to do for the DeckOfCards class Here's my code:

import random
class Card:
'''Create a single card, by id number'''

# Class variables, created once for the class
    suits = [ '\u2660', '\u2661', '\u2662', '\u2663' ]
    ranks = [ 'A','2','3','4','5','6','7','8','9','10','J','Q','K' ]

    def __init__(self, n=0):
    # instance variables for _num, _rank, _suit, _value
    if 0 <= n < 52:
        self._num = n
        self._rank = Card.ranks[n%13]       # note referencing class vars
        self._suit = Card.suits[n//13]
        self._value = n%13 + 1
        if self._rank == 'A':
            self._value = 14
    else: # invalid card indicators
        self._rank = 'x'
        self._suit = 'x'
        self._value = -1

    def __repr__(self):
        return  self._rank + self._suit

    def __lt__(self,other):
        return self._value < other._value

    def __le__(self,other):
        return self._value <= other._value

    def __eq__(self,other):
        return self._value == other._value

class DeckOfCards:
'''A Deck is a collection of cards'''

    def __init__(self):
        self._deck = [ Card(i) for i in range(52) ]

    def __repr__(self):
        return 'Deck : ', self._deck

    def shuffle(self):
        return random.shuffle(self._deck)

    def deal_a_card(self, i=-1):
    #that way player can choose where to draw from 
        return self._deck.pop(i)

    def cards_left(self,count):
        return len(self._deck)

new_deck = DeckOfCards()

此外,请随意评论您想要的任何内容,无论是设计缺陷还是代码冗余,几乎是任何内容.预先感谢!

Also, feel free to comment on anything you'd like, whether it be a design flaw or redundancy in code, literally anything. Thanks in advance!

推荐答案

您应该返回一个字符串类型,例如在Deck中:

You should return a string type, for example in Deck:

def __repr__(self):
    ...
    return 'Deck : '+str(self._deck)

这篇关于如何正确实施/重载"__repr__"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆