简体   繁体   English

如何创建一个命名元组的__repr__?

[英]How to create a __repr__ of a namedtuple?

How do I create a special method __repr__ where I can print, for example, '6 of spades' or 'Q of diamonds' ? 如何创建一种特殊的方法__repr__ ,例如可以打印'6 of spades''Q of diamonds'

How do I access the data from the namedtuple , keeping in mind that I have a list of namedtuple s in self._cards ? 如何从访问数据namedtuple ,记住,我有一个listnamedtuple S IN self._cards

import collections

cards = collections.namedtuple('Card', ['rank', 'suit'])

class Deck:
    ranks = [str(n) for n in range (2,11)] + list('JQKA')
    suits = 'spades diamonds hearts clubs'.split()

    def __init__(self):
        self._cards = [cards(rank, suit) for suit in self.suits for rank in self.ranks]

    def __len__(self):
        return len(self._cards)

    def __getitem__(self, item):
        return self._cards[item]

    def __repr__(self):
        return '%s of %s' % ()  # <-- don't know how to assign the string

b = ()
for i in b:
    print(i)

You could use typing.NamedTuple instead, which allows you to define methods normally: 您可以改用typing.NamedTuple ,它允许您正常定义方法:

from typing import NamedTuple

class Card(NamedTuple):
    rank: str
    suit: str
    def __repr__(self):
        return "{} of {}".format(self.rank, self.suit)

It would be clearer if you renamed cards to Card , since that's the name you assigned to that class: 如果将cards重命名为Card会更清楚,因为这是您为该类分配的名称:

Card = collections.namedtuple('Card', ['rank', 'suit'])

You can extend a namedtuple just like any other class, including to give it __repr__ method. 您可以扩展namedtuple就像任何其他类,包括给它__repr__方法。 You can even reuse the class name, since a class statement is a type of assignment: 您甚至可以重用类名,因为class语句是一种赋值类型:

class Card(Card):
    def __repr__(self):
        return f'{self.rank} of {self.suit}'

A more compact version would be 一个更紧凑的版本是

class Card(collections.namedtuple('Card', ['rank', 'suit'])):
    def __repr__(self):
        return f'{self.rank} of {self.suit}'

It seems like your issue right now is that you are trying to make the __repr__ method inside of your Deck class. 看来您现在的问题是您正在尝试在Deck类中使用__repr__方法。 That method will only get called when you are trying to print Deck objects, however it seems like you are trying to print a message for a single Card instead. 仅当您尝试打印Deck对象时才会调用该方法,但是似乎您正尝试为单个Card打印消息。 You could solve this by making a simple Card class with suit and rank as class variables, and storing a list of Card objects in your deck. 您可以通过创建一个简单的Card类,并使用suit和rank作为类变量来解决此问题,并将Card对象列表存储在您的卡片组中。 This way you could write a __repr__ method for the card class itself, and reference the card's suit and rank directly. 这样,您可以为卡类本身编写__repr__方法,并直接引用卡的衣服和等级。

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

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