如何用 repr 重建对象?

How to rebuild the object with repr?

除了最后一部分,我的代码运行完美。我想用 repr 函数重新创建对象,但它显然不起作用。我在这里和网上都试过了,但我还是很困惑。有什么办法可以做到吗?如果可以,语法是什么?

class Modulo(object):

    def __init__(self, grondtal, waarde = 0):
        self.grondtal = grondtal
        self.waarde = waarde % grondtal

    def __call__(self, m):
        return Modulo(self.grondtal, m)

    def __add__(self, other):
        return Modulo(self.grondtal, self.waarde + other.waarde)

    def __sub__(self, other):
        return Modulo(self.grondtal, self.waarde - other.waarde)

    def __mul__(self, other):
        return Modulo(self.grondtal, self.waarde * other.waarde)

    def __eq__(self, other):
        return self.waarde == other.waarde and self.grondtal == other.grondtal

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return  '[%s %% %s]' % (str(self.grondtal), str(self.waarde))

    def __repr__(self):
        return '%s' %Modulo(self.grondtal, self.waarde)

你可能想要这个:

def __repr__(self):
    return "Modulo(%d,%d)" % (self.grondtal, self.waarde)

或者更通用一点:

def __repr__(self):
    return "%s(%d,%d)" % (self.__class__.__name__, self.grondtal, self.waarde)

例如:

>>> m = Modulo(3,2)
>>> repr(m)
'Modulo(3,2)'