写一个Python C类型,想写一个乘法运算符
Writing a Python C type, and want to write a multiplication operator
我正在用 C 为 Python 编写一个特殊的数字类型作为扩展,我想为它提供一个专门的二进制乘法运算符。
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 */
};
如果我随后编译并加载该库,我可以成功创建名为 x 和 y 的对象的实例。我什至可以
w = x.__mul__(y)
但如果我尝试这样做
w = x * y
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'pyquat.Quat' and 'pyquat.Quat'
有什么方法可以告诉 Python 将 __mul__
视为二进制乘法运算符吗?
如果你想让一个用C写的类型支持乘法,你需要提供一个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。
我正在用 C 为 Python 编写一个特殊的数字类型作为扩展,我想为它提供一个专门的二进制乘法运算符。
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 */
};
如果我随后编译并加载该库,我可以成功创建名为 x 和 y 的对象的实例。我什至可以
w = x.__mul__(y)
但如果我尝试这样做
w = x * y
我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'pyquat.Quat' and 'pyquat.Quat'
有什么方法可以告诉 Python 将 __mul__
视为二进制乘法运算符吗?
如果你想让一个用C写的类型支持乘法,你需要提供一个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。