简体   繁体   中英

I keep getting an attribute error is this

Create a class called Point.

The point should have two attributes:

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

You should override the init (), str (), add (), sub () and mul () methods but my add sub and mul methods keep getting an attribute error AttributeError: 'str' object has no attribute 'x' how do i correct this error?

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

If you want a new Point object, you must create a new objects in your Operator overloaded methods such as __add__, __sub__, __mul__

Eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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