运算符 "is" 和 "in" 的魔术方法名称是什么?
What are the names of the magic methods for the operators "is" and "in"?
我想使用这些运算符的魔术方法进行 bool 二元运算。例如,我可以获得 a < b
作为 getattr(a, '__lt__')(b)
或 a == b
作为 getattr(a, '__eq__')(b)
。
这样可以得到a in b
和a is b
吗?
对于in
,正确的双打方法是__contains__
。
没有is
的方法,因为这等同于id(a) == id(b)
。它比较 Python 在幕后使用的实际对象 ID,因此用于比较对象标识,而不是对象内容。在 class 中覆盖它会破坏 Python 的对象模型,因此不允许。
in
是 __contains__
并且 is
没有 dunder 方法。我强烈建议您使用 operator
module:
中的函数
a < b => operator.lt(a, b)
a == b => operator.eq(a, b)
a in b => operator.contains(a, b)
a is b => operator.is_(a, b)
__contains__
对于 in
是正确的,如果 __contains__
未定义为 __iter__
和 __getitem__
,则具有后备选项。
虽然我不太确定为什么您需要将 getattr
用于 is
;对于 Python 中的 每个 对象,is
是 "defined"。无需通过 operator._is
或(尝试并失败)通过 getattr
。
See the documentation on built-in types:
The behavior of the is
and is not
operators cannot be customized; also they can be applied to any two objects and never raise an exception.
(强调我的)
根据您提供的代码片段,它只是抓取一个函数并使用 getattr(a, "function")(b)
调用它,您已经有了需要评估的对象的名称,只需立即使用 is
;它总是可用的。
我想使用这些运算符的魔术方法进行 bool 二元运算。例如,我可以获得 a < b
作为 getattr(a, '__lt__')(b)
或 a == b
作为 getattr(a, '__eq__')(b)
。
这样可以得到a in b
和a is b
吗?
对于in
,正确的双打方法是__contains__
。
没有is
的方法,因为这等同于id(a) == id(b)
。它比较 Python 在幕后使用的实际对象 ID,因此用于比较对象标识,而不是对象内容。在 class 中覆盖它会破坏 Python 的对象模型,因此不允许。
in
是 __contains__
并且 is
没有 dunder 方法。我强烈建议您使用 operator
module:
a < b => operator.lt(a, b)
a == b => operator.eq(a, b)
a in b => operator.contains(a, b)
a is b => operator.is_(a, b)
__contains__
对于 in
是正确的,如果 __contains__
未定义为 __iter__
和 __getitem__
,则具有后备选项。
虽然我不太确定为什么您需要将 getattr
用于 is
;对于 Python 中的 每个 对象,is
是 "defined"。无需通过 operator._is
或(尝试并失败)通过 getattr
。
See the documentation on built-in types:
The behavior of the
is
andis not
operators cannot be customized; also they can be applied to any two objects and never raise an exception.
(强调我的)
根据您提供的代码片段,它只是抓取一个函数并使用 getattr(a, "function")(b)
调用它,您已经有了需要评估的对象的名称,只需立即使用 is
;它总是可用的。