Home > Back-end >  How to fix Python point class printing error?
How to fix Python point class printing error?

Time:03-19

I'm making a point class in python and I am encountering an error with my makeVectorTo method (a method that takes a second Point as input, and returns a new Vector that goes from starting Point to the second Point). When I try to print it, I am getting this error: AttributeError: 'tuple' object has no attribute 'h'.

How do I get rid of this and print it the way I want?

Here's my code:

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

    def makeVectorTo(self, coor):
      dx = abs(self.x - coor.x)
      dy = abs(self.y - coor.y)
      newCoor = (dx, dy)
      return newCoor

###Testing Point Class###
vec1 = point1.makeVectorTo(point2)
print(vec1.h, vec1.v, "should be 0,3")

The error looked like this:

Traceback (most recent call last):
  File "main.py", line 30, in <module>
    print(vec1.h, vec1.v, "should be 0,3")
AttributeError: 'tuple' object has no attribute 'h'

CodePudding user response:

You are returning a tuple, so you should call by index your 'newCoor'

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

    def makeVectorTo(self, coor):
      dx = abs(self.x - coor.x)
      dy = abs(self.y - coor.y)
      newCoor = (dx, dy)
      return newCoor


point1=Point(1,1)
point2=Point(2,2)


###Testing Point Class###
vec1 = point1.makeVectorTo(point2)
# print(vec1.h, vec1.v, "should be 0,3")
print(vec1[0], vec1[1], "should be 0,3")

CodePudding user response:

As I understand your code, you new to define your Vector Class too

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

    def makeVectorTo(self, coor):
      dx = abs(self.x - coor.x)
      dy = abs(self.y - coor.y)
      return Vector(dx, dy) # Note: calling Vector class


# Note: New Vector class
class Vector:
    def __init__(self, dx, dy):
        self.h = dx
        self.v = dy


# Testing
point1 = Point(0, 0)
point2 = Point(0, 3)
vec1 = point1.makeVectorTo(point2)
print(vec1.h, vec1.v, "should be 0.0,3.0") # Note: expect floats here not int

Note: abs only remove -tive sign for a int. If you want to convert a float into proper number then use int or round

  • Related