Leo*_*aes 3 python oop class operator-overloading
假设我想用__mul__方法定义一个类,例如:
class A():
def __init__(self,*arg,**kwarg):
#some code
def __mul__(self,other):
#some code
Run Code Online (Sandbox Code Playgroud)
如果我这样做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
Run Code Online (Sandbox Code Playgroud)
https://docs.python.org/3/reference/datamodel.html