Python 中 + (pos) 一元运算符的用途是什么? [英] What's the purpose of the + (pos) unary operator in Python?

查看:42
本文介绍了Python 中 + (pos) 一元运算符的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一般来说,一元+在Python中应该做什么?

我之所以这么问是因为到目前为止,我从未见过这样的情况:

+obj != obj

其中 obj 是实现 __pos__() 的通用对象.

所以我想知道:为什么 +__pos__() 存在?您能否提供一个真实示例,其中上述表达式的计算结果为 True?

解决方案

以下是 decimal 包中的真实世界"示例:

<预><代码>>>>从十进制导入十进制>>>obj = 十进制('3.1415926535897932384626433832795028841971')>>>+obj != obj # __pos__ 函数四舍五入到正常精度真的>>>对象十进制('3.1415926535897932384626433832795028841971')>>>+物件十进制('3.141592653589793238462643383')

Generally speaking, what should the unary + do in Python?

I'm asking because, so far, I have never seen a situation like this:

+obj != obj

Where obj is a generic object implementing __pos__().

So I'm wondering: why do + and __pos__() exist? Can you provide a real-world example where the expression above evaluates to True?

解决方案

Here's a "real-world" example from the decimal package:

>>> from decimal import Decimal
>>> obj = Decimal('3.1415926535897932384626433832795028841971')
>>> +obj != obj  # The __pos__ function rounds back to normal precision
True
>>> obj
Decimal('3.1415926535897932384626433832795028841971')
>>> +obj
Decimal('3.141592653589793238462643383')

这篇关于Python 中 + (pos) 一元运算符的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆