0

This is a vector class that I have been making, however, when I try to run it, it gives the following error: "NameError: name 'self' is not defined"

If anyone could tell me what is going wrong, that would be much appreciated.

I am fairly new to Python so any feedback on how to improve/optimize the code is appreciated as well.

class Vector(object):

    @staticmethod
    def __init__(self,x,y):
        self.x = x
        self.y = y


    @staticmethod   
    def __add__(self, newVector):
        return Vector(self.x+newVector.x, self.y+newVector.y)


    @staticmethod
    def __subtract__(self,newVector):
        return Vector(self.x-newVector.x, self.y-newVector.y)


    @staticmethod
    def __dotProduct__(self, newVector):
        return (self.x*other.x) + (self.y*other.y)


    @staticmethod
    def __length__(self, newVector):
        return sqrt((self.y)^2 + (self.x)^2)


    @staticmethod
    def __xTheta__ (self, Vector):
        return math.atan(math.degrees(self.y/self.x))


    @staticmethod
    def __yTheta(self, Vector):
        return math.atan(math.degrees(self.x/self.y))


    @staticmethod
    def __resolveX__(self, Vector):
        return Vector(self.x, 0)


    @staticmethod
    def __resolveY__(self, Vector):
        return Vector(0, self.y)


    @staticmethod
    def __scalarProduct__(self, scalar):
        return Vector(self.x*scalar, self.y * scalar)


    @staticmethod
    def __normalise__(self, Vector):
        return Vector(self.x/self.length(Vector),self.y/self.length(Vector))


a = Vector(3,4)
print(a.length())
n8sty
  • 1,418
  • 1
  • 14
  • 26
Bob
  • 51
  • 5
  • Remove all of your @staticmethods – Alan Kavanagh Sep 22 '17 at 13:37
  • 2
    Yeah -- the presence of `self` in the argument list means they _aren't_ staticmethods. – John Gordon Sep 22 '17 at 13:44
  • But when I do that, it gives another error: attribute error: 'Vector' has no attribute 'length'. – Bob Sep 22 '17 at 20:36
  • @Bob that's because you named the attribute `__length__` which is kind of like the built-in `__len__` but not which is what the `len` function uses to return the length of an object. Look here: https://docs.python.org/3/reference/datamodel.html#object.__len__. `len` also needs to return an `int` which your implementation won't do in most cases. This should help you too: https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name – n8sty Sep 22 '17 at 23:55

0 Answers0