【问题标题】:How can I fix the error with __repr__ in python?如何在 python 中使用 __repr__ 修复错误?
【发布时间】:2020-08-27 22:49:45
【问题描述】:

我想创建一个函数来生成具有相应系数的多项式。

class Polynomial:
    def __init__(self, *coefficients):
        self.coefficients = coefficients
    def __len__(self):
        return len(self.coefficients)
    def __repr__(self):
        equation = ""
        for i in range(len(self)):
            if i == 0:
                equation += "(" + str(self.coefficients[i]) + "x^" + str(i)
            else:
                equation += "+" + str(self.coefficients[i]) + "x^" + str(i)
            return equation + ")"
    def __lt__(self, other):
        return self.coefficients < other.coefficients
    def __ge__(self, other):
        return self.coefficients >= other.coefficients 
a = Polynomial(1,2,3)
print(a)

我希望打印 '(1x^0+2x^1+3x^2)',但它只是 (1x^0)。 我的代码会出现什么问题?提前谢谢你。

【问题讨论】:

    标签: python class repr


    【解决方案1】:

    在您返回的 repr 方法中过度缩进。我还建议将您的系数存储为一个列表,以便使用任何可迭代对象轻松构建。

    def __init__(self, coefficients):
        self.coefficients = list(coefficients)
    

    【讨论】:

      【解决方案2】:

      您从错误的缩进返回 [[equation + ")"]]。循环仅运行一次迭代 i = 0。 你的代码:

      for i in range(len(self)):
                  if i == 0:
                      equation += "(" + str(self.coefficients[i]) + "x^" + str(i)
                  else:
                      equation += "+" + str(self.coefficients[i]) + "x^" + str(i)
      ------->    return equation + ")"
      

      改为:

      for i in range(len(self)):
                  if i == 0:
                      equation += "(" + str(self.coefficients[i]) + "x^" + str(i)
                  else:
                      equation += "+" + str(self.coefficients[i]) + "x^" + str(i)
      return equation + ")"
      

      【讨论】:

        【解决方案3】:

        正如其他人已经指出的那样,repper 的问题在于 return 语句的缩进级别错误。

        一个可以说更深、更重要的问题是,您的预期 repper 不允许使用 eval(repr(my_poly)) 重新创建一个相同的对象 - 在您的示例中是 eval('Polynomial(1, 2, 3)')

        this answer中提到:

        ...__str__ 的目的是可读的,而目的 的__repr__ 是明确的。

        以下示例使用您的原始(和更正)repper 作为__str__ 方法,并添加您的同行期望的repper。使用__class__ 将使您的子类也能够直接使用它。

        class Polynomial:
        
            def __init__(self, *coefficients):
                self.coefficients = tuple(coefficients)
        
            def __len__(self):
                return len(self.coefficients)
        
            def __str__(self):
                equation = ""
                for degree, factor in enumerate(self.coefficients):
                    if degree == 0:
                        equation += "(" + str(factor) + "x^" + str(degree)
                    else:
                        equation += " + " + str(factor) + "x^" + str(degree)
                return equation + ")"
        
            def __repr__(self):
                return f'{self.__class__}{tuple(self.coefficients)}'
        
        
        my_poly = Polynomial(1, 2, 3)
        
        print(my_poly)     # (1x^0 +2 x^1 + 3x^2)
        print([my_poly])   # ['Polynomial(1, 2, 3)']
        

        【讨论】:

          【解决方案4】:

          最突出的问题是for循环内的return语句。

          class Polynomial:
              def __init__(self, *coefficients):
                  self.coefficients = coefficients
              def __len__(self):
                  return len(self.coefficients)
              def __repr__(self):
                  equation = "("
                  for i in range(len(self)):
                      if i != 0:
                          equation += "+"
                      equation += str(self.coefficients[i]) + "x^" + str(i)
                  return equation + ")"
              def __lt__(self, other):
                  return self.coefficients < other.coefficients
              def __ge__(self, other):
                  return self.coefficients >= other.coefficients 
          a = Polynomial(1,2,3)
          print(a)
          

          【讨论】:

            猜你喜欢
            • 2019-10-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-29
            相关资源
            最近更新 更多