[英]how do i implement a operation between built-in objects and created classes the other way around in python?
假设我想用__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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.