获取传递给 eval 时具有相同值的 __repr__ 到 return 字符串?

Get __repr__ to return string that has same value when passed to eval?

我不完全明白这里发生了什么。为什么从 repr 返回的字符串评估为 False?如果有人可以扩展我在这里不理解的内容,那将不胜感激。

class Bag(object):
    def __init__(self, iter_vals = []):
        self.iter_vals = iter_vals
        
    def __repr__(self):
        return f"Bag({str(self.iter_vals)})"
        
        
if __name__ == '__main__':
    b = Bag(['d','a','b','d','c','b','d'])
    print(eval(repr(b)) == b)

>>> False

你还需要定义一个__eq__方法来定义如何一个Bag等于另一个Bag:

class Bag(object):
    def __init__(self, iter_vals = []):
        self.iter_vals = iter_vals
        
    def __repr__(self):
        return f"Bag({str(self.iter_vals)})"

    def __eq__(self, other):
        if not isinstance(other,Bag):
            raise TypeError('not a Bag')
        return self.iter_vals == other.iter_vals
        
if __name__ == '__main__':
    b = Bag(['d','a','b','d','c','b','d'])
    print(eval(repr(b)) == b)  # True