繁体   English   中英

我如何在python中实现内置对象和创建类之间的操作?

[英]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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM