Home > Blockchain >  I keep getting an attribute error is this
I keep getting an attribute error is this

Time:01-15

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

CodePudding user response:

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
  • Related