猫史档案馆


python喵之重载运算符

用户:悦qr8R悦qr8R查看:0 回复:0 评论:0 创建时间:2021-12-12T12:53:13


提示:本帖科普向,大佬不喜勿喷

如果有需要的话请在csdn博客搜索

重载运算符,就是新定义数据类型,一般在class下使用。

如下:

 方法名                  运算符和表达式      说明
            __add__(self,rhs)        self + rhs        加法
            __sub__(self,rhs)        self - rhs         减法
            __mul__(self,rhs)        self * rhs         乘法
            __truediv__(self,rhs)   self / rhs          除法
            __floordiv__(self,rhs)  self //rhs          地板除
            __mod__(self,rhs)       self % rhs       取模(求余)
            __pow__(self,rhs)       self **rhs         幂运算

当然,我们还可以。。

class out:
    def __init__(self, data=""):
        self.v=data
        pass
    def __lshift__(self, other):
        print(other.v)
        pass
    pass
i=out()
i<<out("hello")

nb吧?

__lshift__是左移运算符的重载。

__rshift__右移

还是看上面程序的结果吧

center_image

很像c++的cout<<吧??


回复

上一页1 页 / 共 0下一页