重新定义 __and__ 运算符

发布于 2024-08-30 03:32:52 字数 399 浏览 2 评论 0原文

为什么我无法重新定义 __and__ 运算符?

class Cut(object):
      def __init__(self, cut):
         self.cut = cut
      def __and__(self, other):
         return Cut("(" + self.cut + ") && (" + other.cut + ")")

a = Cut("a>0") 
b = Cut("b>0")
c = a and b
print c.cut()

我想要 (a>0) && (b>0),但我得到了 b,即 的通常行为

Why I can't redefine the __and__ operator?

class Cut(object):
      def __init__(self, cut):
         self.cut = cut
      def __and__(self, other):
         return Cut("(" + self.cut + ") && (" + other.cut + ")")

a = Cut("a>0") 
b = Cut("b>0")
c = a and b
print c.cut()

I want (a>0) && (b>0), but I got b, that the usual behaviour of and

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

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

发布评论

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

评论(2

多孤肩上扛 2024-09-06 03:32:52

__and__ 是二元(按位)& 运算符,而不是逻辑and 运算符。

由于 and 运算符是短路运算符,因此无法将其实现为函数。也就是说,如果第一个参数为 false,则根本不会计算第二个参数。如果您尝试将其实现为函数,则必须先对两个参数进行求值,然后才能调用该函数。

__and__ is the binary (bitwise) & operator, not the logical and operator.

Because the and operator is a short-circuit operator, it can't be implemented as a function. That is, if the first argument is false, the second argument isn't evaluated at all. If you try to implement that as a function, both arguments have to be evaluated before the function can be invoked.

心如荒岛 2024-09-06 03:32:52

因为你无法在 Python 中重新定义关键字(这就是 and 的意思)。 __add__ 用于执行其他操作:

调用这些方法来实现二进制算术运算(...<代码>&...

because you cannot redefine a keyword (that's what and is) in Python. __add__ is used to do something else:

These methods are called to implement the binary arithmetic operations (...&...

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