singledispatch in class, how to dispatch self type

Posted by yanxinyou on Stack Overflow See other posts from Stack Overflow or by yanxinyou
Published on 2014-06-05T15:06:55Z Indexed on 2014/06/05 15:24 UTC
Read the original article Hit count: 139

Filed under:
|
|
|

Using python3.4. Here I want use singledispatch to dispatch different type in __mul__ method . The code like this :

class Vector(object):

    ## some code not paste  
    @functools.singledispatch
    def __mul__(self, other):
        raise NotImplementedError("can't mul these type")

    @__mul__.register(int)
    @__mul__.register(object)                # Becasue can't use Vector , I have to use object 
    def _(self, other):
        result = Vector(len(self))           # start with vector of zeros
        for j in range(len(self)):
            result[j] = self[j]*other
        return result

    @__mul__.register(Vector)                # how can I use the self't type
    @__mul__.register(object)                # 
    def _(self, other):
        pass # need impl 

As you can see the code , I want support Vector*Vertor , This has Name error

Traceback (most recent call last):
  File "p_algorithms\vector.py", line 6, in <module>
    class Vector(object):
  File "p_algorithms\vector.py", line 84, in Vector
    @__mul__.register(Vector)                   # how can I use the self't type
NameError: name 'Vector' is not defined

The question may be How Can I use class Name a Type in the class's method ? I know c++ have font class statement . How python solve my problem ? And it is strange to see result = Vector(len(self)) where the Vector can be used in method body .

© Stack Overflow or respective owner

Related posts about python

Related posts about class