将对象与repr()进行比较会抛出NameError

时间:2016-09-20 20:01:09

标签: python class eval repr

所以我试图将Deck对象与Deck对象的评估表示进行比较并获得

Traceback (most recent call last):
  File "C:/Users/Philipp/PycharmProjects/fnaround/src.py", line 3, in <module>
    print(Deck() == eval(repr(Deck())))
  File "<string>", line 1, in <module>
NameError: name 'Card' is not defined

我无法弄清楚它是什么,因为我也覆盖了其他类中的__repr__方法,并且它工作正常。我认为它与它从Deck类跳到Card类有关,但我不确定。有人可以向我解释程序如何在类中移动以及如何修复错误。谢谢

class Deck:

    suits = ['\u2660', '\u2661', '\u2662', '\u2663']
    ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']

    def __init__(self):

        self.deck = []

        for suit in self.suits:
            for rank in self.ranks:
                self.deck.append(Card(rank, suit))

    def __repr__(self):
        return 'Deck({})'.format(self.deck)

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

class Card:

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

    def __repr__(self):
        return "Card('{}', '{}')".format(self.rank, self.suit)

    def __eq__(self, other):
        return self.rank == other.rank and self.suit == other.suit

print(Deck() == eval(repr(Deck())))

3 个答案:

答案 0 :(得分:0)

您的Deck类不带参数,但您的表示形式会将卡列表作为参数传递。您可以将Deck.__init__更改为以下内容:

def __init__(self, deck=None):
    if deck:
        self.deck = deck
    else:
        self.deck = [Card(r, s) for r in self.ranks for s in self.suits]

最终的比较也应该如你所愿。

答案 1 :(得分:0)

我得到了这个输出;

deck.py", line 32, in <module>
  print(Deck() == eval(repr(Deck())))
File "<string>", line 1, in <module>
TypeError: __init__() takes 1 positional argument but 2 were given
<<< Process finished. (Exit code 1)

你的repr试图将第二个参数传递给Deck__init__()。它只需要一个。这工作

def __repr__(self):
    return 'Deck()'.format(self.deck)

答案 2 :(得分:0)

当前问题(导致NameError)是当您在eval实例的Deck上运行repr时, #39; t在本地命名空间中具有名称Card。这意味着当eval尝试解释repr(Deck())返回的字符串时,它会在遇到第一个Card时失败。

您只需将Card以及Deck导入到您运行其他代码的命名空间中即可解决问题的这一部分:

from deck_module import Deck  # you've not said what your module names are,
from card_module import Card  # so I'm making these up

eval(repr(Deck())) # raises a TypeError, but not a ValueError any more

添加import类的Card并不会使代码生效(由于Deck构造函数的缺点),但至少它会让你超越NameError