如何使用 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)'    

最新更新