栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python中的运算符重载,对象在运算符的右侧

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python中的运算符重载,对象在运算符的右侧

是。例如,有

__radd__
。另外,没有用于
__le__()
__ge__()
等的对象,但是正如乔尔·科内特(Joel
Cornett)正确地观察到的那样,如果仅定义
__lt__
,则
a > b
调用的
__lt__
功能
b
,这提供了一种解决方法。

>>> class My_Num(object):...     def __init__(self, val):...         self.val = val...     def __radd__(self, other_num):...         if isinstance(other_num, My_Num):...  return self.val + other_num.val...         else:...  return self.val + other_num... >>> n1 = My_Num(1)>>> n2 = 3>>> >>> print n2 + n14>>> print n1 + n2Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: unsupported operand type(s) for +: 'My_Num' and 'int'

请注意,至少在某些情况下,这样做是合理的:

>>> class My_Num(object):...     def __init__(self, val):...         self.val = val...     def __add__(self, other_num):...         if isinstance(other_num, My_Num):...  return self.val + other_num.val...         else:...  return self.val + other_num...     __radd__ = __add__


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639658.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号