singledispatchmethod using class it is used in?

105 Views Asked by At

For practice I am trying to build a class for 2d vectors, I want to override the multiplication operator to be able to multiply a vector by a scalar, but also by another vector (dot product). This single argument based polymorphism is normally achieved using the @functools.singledispatchmethod decorator. My problem is that from what I've found online, I cannot refer to the class that I'm defining as a type within its own body. I wish to do this in order to define a variation of mul function, and register it to receive type 'vector', which is the very type I am defining in this body.. Is there an elegant way to do this ?

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

    @functools.singledispatchmethod
    def __mul__(self, x):
        pass

    @__mul__.register(int)
    def mul_by_scalar(self, s):
        return vector(self.x * s, self.y * s)

    @__mul__.register(vector)
    def mul_by_vec(self, v):
        return self.x*v.x + self.y*v.y

When I run it, Python expectedly doesn't recognise "vector".

0

There are 0 best solutions below