user3842385
user3842385

Reputation: 67

AttributeError: 'Vector' object has no attribute 'plus' while adding new method in class Vector using python 2.7

I am trying to add new method to the class Vector in python 2.7, while running the program, it return error message no attribute for the method created in python class. the source code is following:

class Vector(object):
     def __init__(self, coordinates):
          try:
              if not coordinates:
                   raise ValueError
              self.coordinates = tuple(coordinates)
              self.dimension = len(coordinates)
          except ValueError:
              raise ValueError('The coordinates must be nonempty')
          except TypeError:
              raise TypeError('The coordinates must be an iterable')
     def __str__(self):
          return 'Vector: {}'.format(self.coordinates)
     def __eq__(self, v):
          return self.coordinates == v.coordinates
     def plus(self, v):
          new_coordinates = [x+y for x, y in zip(self.coordinates, v.coordinates)]
          return Vector(new_coordinates)

myVector1 = Vector([8.218, -9.341])
myVector2 = Vector([-1.129, 2.111])
print myVector1.plus(myVector2)
output error message:
AttributeError: 'Vector' object has no attribute 'plus'

Upvotes: 0

Views: 1340

Answers (1)

Netwave
Netwave

Reputation: 42756

You did not scoped the functions properly, the methods must be inside the class:

class Vector(object):
    def __init__(self, coordinates):
        try:
            if not coordinates:
                raise ValueError
            self.coordinates = tuple(coordinates)
            self.dimension = len(coordinates)

        except ValueError:
            raise ValueError('The coordinates must be nonempty')

        except TypeError:
            raise TypeError('The coordinates must be an iterable')

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

    def __eq__(self, v):
        return self.coordinates == v.coordinates

    def plus(self, v):
            new_coordinates = [x + y for x,y in zip(self.coordinates, v.coordinates)]
            return Vector(new_coordinates)

Upvotes: 1

Related Questions