返回整数的 Python 运算符

发布于 2024-08-31 07:20:06 字数 271 浏览 11 评论 0原文

有没有办法让Python运算符行“==”和“>”返回整数而不是布尔值。我知道我可以使用 int 函数 (int(1 == 1)) 或添加 0 ((1 == 1) + 0) 但我想知道是否有一个简单的方法可以做到这一点。就像当您希望除法返回浮点数时,您可以输入 from __future__ import div。有没有办法让运算符返回整数来做到这一点?或者我可以创建一个扩展 __future__._Feature 的类来实现我想要的功能吗?

Is there any way to have Python operators line "==" and ">" return ints instead of bools. I know that I could use the int function (int(1 == 1)) or add 0 ((1 == 1) + 0) but I was wondering if there was an easy way to do it. Like when you want division to return floats you could type from __future__ import division. Is there any way to do this with operators returning ints? Or could I make a class extending __future__._Feature that would do what I want?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

救赎№ 2024-09-07 07:20:07

不,你不能。当 Guido 统一类型和类时,他找到了一种覆盖内置类型行为的方法(由于他实现事物的方式),但他声明它是一个错误并堵塞了漏洞。禁止更改内置类型的行为(除了您的示例 - 从未来导入除法,这是有充分理由的)。

抱歉,我找不到邮件列表帖子。但我记得它,因为它很有趣。

No, you can't. When Guido unified types and classes, he found a way to override the behavior of built-in types (due to the way he implemented things), but he declared it a bug and plugged the loophole. Changing the behavior of built-in types (except for your example - importing division from future, which is there for a good reason) is forbidden.

Sorry, but I can't find the mailing list post. I remember it though, as it was quite interesting.

戏蝶舞 2024-09-07 07:20:06

您不能覆盖内置的比较函数。从某种意义上说,比较运算符已经返回了intboolint 的子类,因此您可以对它执行任何可以对 int 执行的操作。那么问题就变成了为什么你想让比较返回 int 对象,而不是 bool 对象?

You cant override the built-in comparison functions. In some sense the comparison operators are already returning int. bool is a subclass of int, so you can do anything to it that you can do to a int. The question then becomes why would you want to have comparisons return int objects, not bool objects?

年少掌心 2024-09-07 07:20:06

根据您的说明,您可以将比较运算符更改为以下内容:

stack.push(1 if stack.pop() > stack.pop() else 0)

这会将 > 的布尔结果转换为 10 作为你会喜欢的。

另外,在同一表达式中调用 stack.pop() 两次时要小心。您(当然)不知道参数将以什么顺序进行计算,并且 Python 的不同实现很可能会以不同的顺序弹出参数。您将需要使用临时变量:

x = stack.pop()
y = stack.pop()
stack.push(1 if x > y else 0)

Based on your clarification, you might change your comparison operator to something like:

stack.push(1 if stack.pop() > stack.pop() else 0)

This will convert the boolean result of > to 1 or 0 as you would like.

Also, be careful about calling stack.pop() twice in the same expression. You don't know (for sure) what order the arguments will be evaluated in, and different implementations of Python may very well pop the arguments in a different order. You will need to use temporary variables:

x = stack.pop()
y = stack.pop()
stack.push(1 if x > y else 0)
土豪 2024-09-07 07:20:06

您可以让自定义类的比较运算符返回您喜欢的任何内容 - 只需实现相关方法(__eq____ne____gt__、< code>__lt__, __ge__, __le__) 返回您想要的内容。对于您无法控制的对象,您无法更改此设置,但应该没有必要这样做:布尔整数,因为里氏替换原则。注意到内置类型的 __eq__ 方法返回的 bool 与任何其他整数之间存在差异的代码使用了错误的结果。

__future__ 模块在这里不相关;你不能用它来做任何你想做的事,你只能用它来更改添加到Python中的特定设置。您可以使用 __future__ 导入将除法转换为真正的除法,因为 Python 中已添加了除法。添加更多 __future__ 导入的唯一方法是修改 Python 本身。

You can have the comparison operators of your custom classes return whatever you like -- simply implement the relevant methods (__eq__, __ne__, __gt__, __lt__, __ge__, __le__) to return what you want. For objects that you don't control you cannot change this, but there should be no need to: bools are ints, because of the Liskov substitution principle. Code that notices a difference between the bool returned by the builtin types' __eq__ methods and any other integer is using the result wrong.

The __future__ module isn't relevant here; you can't use it to do whatever you want, you can only use it to change specific settings that were added to Python. You can turn division into true division with the __future__ import because that's what was added to Python. The only way to add more __future__ imports is by modifying Python itself.

陪你搞怪i 2024-09-07 07:20:06

在您自己的对象上,很容易覆盖每个比较运算符。对于内置函数,覆盖方法是“只读”的,因此我所有设置它们的尝试都不会成功。

>>> class foo:
   def __lt__(self, other):
      return cmp(5, other)

>>> f = foo()
>>> f<3
1
>>> f<7
-1
>>> f<5
0

>>> j=""
>>> j.__lt__=lambda other: cmp(5, other)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'str' object attribute '__lt__' is read-only

On your own objects, it is easy to override each comparison operator. For built-ins, the override methods are "read only" so all my attempts to set them don't pan out.

>>> class foo:
   def __lt__(self, other):
      return cmp(5, other)

>>> f = foo()
>>> f<3
1
>>> f<7
-1
>>> f<5
0

>>> j=""
>>> j.__lt__=lambda other: cmp(5, other)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'str' object attribute '__lt__' is read-only
恰似旧人归 2024-09-07 07:20:06

将你的 bool 转换为 int ?

<代码>>> int(True)

1

>>>>> int(False)

0

或者将其转换为 str?

<代码>>> str(int(True))

'1'

>>>>> str(int(False))

'0'

Cast your bool to an int?

>>> int(True)

1

>>> int(False)

0

Or cast that to a str?

>>> str(int(True))

'1'

>>> str(int(False))

'0'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文