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