除了最后一部分,我的代码完美无缺。我想用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)
答案 0 :(得分:4)
你可能想要这个:
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)'