Sam*_*rad 2 python repr representation
除了最后一部分,我的代码工作正常。我想用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)
Run Code Online (Sandbox Code Playgroud)
您可能想要这样:
def __repr__(self):
return "Modulo(%d,%d)" % (self.grondtal, self.waarde)
Run Code Online (Sandbox Code Playgroud)
或者,更通用一些:
def __repr__(self):
return "%s(%d,%d)" % (self.__class__.__name__, self.grondtal, self.waarde)
Run Code Online (Sandbox Code Playgroud)
例如:
>>> m = Modulo(3,2)
>>> repr(m)
'Modulo(3,2)'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |