1

I'm writing a special numerical type for Python in C as an extension, and I want to provide it with a specialized binary multiplication operator.

static PyMethodDef pyquat_Quat_methods[] = {
  {"__mul__", (PyCFunction)pyquat_Quat_mul, METH_O, "multiply unit quaternion by another using the Hamiltonian definition"},
  {NULL, NULL, 0, NULL}  /* Sentinel */
};

If I then compile and load the library, I can successfully create instances of the object called x and y. I can even do

w = x.__mul__(y)

But if I try to do

w = x * y

I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'pyquat.Quat' and 'pyquat.Quat'

Is there some way I need to tell Python to treat __mul__ as the binary multiplication operator?

Translunar
  • 3,739
  • 33
  • 55
  • Overloading operators seems to be possible with classes, so e.g. *, + between two objects of the class can be defined using _ _mul_ _ and _ _add_ _ (had to add the space between the _ or the double _ gets consumed as bold formatting) method definitions in the class, see http://blog.teamtreehouse.com/operator-overloading-python. BTW all I did was search for _python operator overload_ and this was the top answer. See also http://stackoverflow.com/questions/1936135/operator-overloading-in-python – DisappointedByUnaccountableMod Jan 11 '16 at 17:05
  • @barny - re: formatting. Try adding backticks: `\`__mul__\`` – Robᵩ Jan 11 '16 at 17:09
  • doh knew that worked in answer, never tried it in comment. Thanks! – DisappointedByUnaccountableMod Jan 11 '16 at 17:09
  • @barny: That's what the questioner already tried, and it didn't work, because the C API way of overloading operators is different. – user2357112 Jan 11 '16 at 17:09

1 Answers1

4

If you want a type written in C to support multiplication, you need to provide a tp_as_number field with an nb_multiply function for multiplication, and you need to not explicitly provide a __mul__ method. __mul__ will be handled for you. It may help to look at how built-in types do it.

user2357112
  • 260,549
  • 28
  • 431
  • 505