开发者

override builtin "and"

开发者 https://www.devze.com 2023-02-19 23:05 出处:网络
can the primitive \"and\" be overridden? for instance If I try to do something like this class foo(): def __and__(self,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(sel开发者_JS百科f) ):
           return self
    else:
           return other


__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__


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消