繁体   English   中英

我不断收到属性错误是这个

[英]I keep getting an attribute error is this

创建一个名为 Point 的 class。

该点应具有两个属性:

Attribute Name      Description
x             x-coordinate of the point
y             y-cordinate of the point

您应该重写init ()、 str ()、 add ()、 sub () 和mul () 方法,但我的 add sub 和 mul 方法不断收到属性错误 AttributeError: 'str' 882829995402888 has no attribute 'x' 怎么办我纠正这个错误?

class Point: 
  def __init__(self,x,y):
    self.x=x
    self.y=y

  def __str__(self):
    return_string = "Instance of Point\n\n"
    return_string += f"x: {self.x}\ny: {self.y}"
    return return_string

  def __add__(self, other):
    print("Instance of Point\n")
    return(f"x: {self.x + other.x}\ny: {self.y + other.y}")
    return

  def __sub__(self,other):
    print("Instance of Point\n")
    return(f"x: {self.x - other.x}\ny: {self.y-other.y}")

  def __mul__(self, other):
    print("Instance of Point\n")
    return(f"x: {self.x * other.x}\ny: {self.y * other.y}")

  def __eq__(self, other):
    if self.x == other.x and self.y == other.y:
      return True
    else:
      return False

  """ A simple representation of a point in 2d space"""
  pass


if __name__ == "__main__":
  point_one = Point(3,2)
  print(point_one)
  print()
  point_two = Point(5,3)
  print(point_two)
  print()
  point_three = point_one + point_two
  print(point_three)
  print()
  point_four = point_one - point_two
  print(point_four)
  print()
  point_five = point_one * point_two
  print(point_five)
  print()
  print(point_one == point_two) # prints False

如果你想要一个新的Point object,你必须在你的 Operator 重载方法中创建一个新的对象,例如__add__, __sub__, __mul__

例如:

 def __add__(self, other):
    print("Instance of Point\n")
    newPoint = Point(self.x + other.x, self.y + other.y)
    return newPoint

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM