__mul__ vs __rmul__ (and others) priority for different classes

Discussion in 'Python' started by dmitrey, Dec 11, 2009.

  1. dmitrey

    dmitrey Guest

    hi all,
    I have created a class MyClass and defined methods like __add__,
    __mul__, __pow__, __radd__, __rmul__ etc.
    Also, they are defined to work with numbers, Python lists and

    Both Python lists and numpy arrays have their own methods __add__,
    __mul__, __pow__, __radd__, __rmul__ etc.
    If I involve myPythonList * myClassInstance it returns just result of
    my __rmul__; but when I invoke nuumpy_arr*myClassInstance it returns
    another numpy array with elements [nuumpy_arr[0]*myClassInstance,
    nuumpy_arr[1]*myClassInstance, ...].

    Can I somehow prevent numpy array of using it __mul__ etc methods?
    (and use only my __rmul__, __radd__, etc instead)?

    Thank you in advance, D.
    dmitrey, Dec 11, 2009
    1. Advertisements

  2. dmitrey

    Terry Reedy Guest

    No. you have to put your class instance first to get priority.
    Given a op b, python first calls a.__op__(b) and only if that fails,
    which it will for most builtin objects when b is MyClass, b.__rop__(a).
    Numpy arrays, however, are more broadminded about what they will work with.

    If your operations are not commutative, you will either have to wrap
    numpy arrays in a class that disables the special methods or use
    explicit function calls.

    Terry Jan Reedy
    Terry Reedy, Dec 11, 2009
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.