覆盖内置的“and”
原始的“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
__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__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 foror
.布尔型
and
和or
在 Python 中无法被覆盖。确实,它们具有特殊行为(短路,因此两个操作数并不总是被评估),这与它们不可重写的原因有关。然而,这并不是(恕我直言)故事的全部。事实上,Python可以提供一种支持短路的工具,同时仍然允许覆盖
and
和or
运算符;它根本不这样做。这可能是为了让事情变得简单而故意选择的,也可能是因为 Python 开发人员认为还有其他事情对开发人员更有用,并且正在研究它们。然而,这是Python设计者的选择,而不是自然法则。
Boolean
and
andor
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
andor
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.