代码之家  ›  专栏  ›  技术社区  ›  Sam Farjamirad

如何使用repr重建对象?

  •  2
  • Sam Farjamirad  · 技术社区  · 7 年前

    除了最后一部分,我的代码运行得很好。我想用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)
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   randomir    7 年前

    您可能想要:

    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)'