python - 我如何在 python 中以相反的方式实现内置对象和创建的类之间的操作?

标签 python class oop operator-overloading

假设我想用 __mul__ 方法定义一个类,例如:

class A():
    def __init__(self,*arg,**kwarg):
        #some code
    def __mul__(self,other):
        #some code

如果我执行A()*2,它会给我一个结果。但是当我尝试相反的方法时 (2*A()),它不起作用。 有没有办法以其他方式实现这种操作?

最佳答案

你会使用object.__rmul__(self, other):

class A():
    def __init__(self, *arg, **kwarg):
        #some code
    def __mul__(self, other):
        #some code
    def __rmul__(self, other):
        return self * other

https://docs.python.org/3/reference/datamodel.html

关于python - 我如何在 python 中以相反的方式实现内置对象和创建的类之间的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256150/

相关文章:

python - 如何使用 python 3 对文件执行上下文菜单操作

python - 将字符串列表转换为元组列表

c++ - 为什么取消引用字符串 vector 迭代器需要括号?

python - for 循环中的 if/else

内存管理

javascript - JavaScript 中的错误代码?

python - 静态类在导入时初始化。 python 2如何在导入时初始化静态类

class - Unity JS 怎么有一个类?

ruby - "if/unless"等是什么类

c++ - 如何使用 std::function 或 Boost 在 C++ 中实现类成员指针?