覆盖内置的“and”

发布于 2024-10-27 07:32:47 字数 437 浏览 1 评论 0原文

原始的“and”可以被覆盖吗? 例如,如果我尝试做这样的事情

class foo():
    def __and__(self,other):
          return "bar"

,就会输出

>> foo() and 4
4
>> foo().__and__(4)
'bar'

我的直觉,内置的 and 不能被覆盖,也不应该被覆盖,以免引起混乱。

我想 and 函数不应该改变,因为它不需要改变,因为它的行为就像

def and(self,other):
    if( not bool(self) ):
           return self
    else:
           return other

can the primitive "and" be overridden?
for instance If I try to do something like this

class foo():
    def __and__(self,other):
          return "bar"

this gets outputted

>> foo() and 4
4
>> foo().__and__(4)
'bar'

my intuition is that the built in and cannot be overridden and shouldn't be overridden to not cause confusion.

I guess the and function shouldn't be changed because it doesn't need to be, since it behaves like

def and(self,other):
    if( not bool(self) ):
           return self
    else:
           return other

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

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

发布评论

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

评论(3

夕色琉璃 2024-11-03 07:32:47

__and__ 覆盖按位运算符 &,而不是逻辑运算符。

要为类提供布尔逻辑处理,请定义一个 __nonzero__ 方法: http:// docs.python.org/reference/datamodel.html#object.__nonzero__

__and__ overrides the bitwise operator &, not the logic operator.

To give your class boolean logic handling, define a __nonzero__ method: http://docs.python.org/reference/datamodel.html#object.__nonzero__

起风了 2024-11-03 07:32:47

and 运算符无法被覆盖,因为它并不总是评估其两个操作数。没有办法提供一个可以执行其功能的函数,函数的参数始终在调用函数之前进行完全评估。 也是如此。

The and operator cannot be overridden, since it doesn't always evaluate both of its operands. There is no way to provide a function that can do what it does, arguments to functions are always fully evaluated before the function is invoked. The same goes for or.

(り薆情海 2024-11-03 07:32:47

布尔型 andor 在 Python 中无法被覆盖。确实,它们具有特殊行为(短路,因此两个操作数并不总是被评估),这与它们不可重写的原因有关。然而,这并不是(恕我直言)故事的全部。

事实上,Python可以提供一种支持短路的工具,同时仍然允许覆盖 andor 运算符;它根本不这样做。这可能是为了让事情变得简单而故意选择的,也可能是因为 Python 开发人员认为还有其他事情对开发人员更有用,并且正在研究它们。

然而,这是Python设计者的选择,而不是自然法则。

Boolean and and or can't be overridden in Python. It is true that they have special behavior (short-circuiting, such that both operands are not always evaluated) and this has something to do with why they are not overrideable. However, this is not (IMHO) the whole story.

In fact, Python could provide a facility that supports short-circuiting while still allowing the and and or operators to be overridden; it simply does not do so. This may be a deliberate choice to keep things simple, or it may be because there are other things the Python developers think would be more useful to developers and are working on them instead.

However, it is a choice on the part of Python's designers, not a law of nature.

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