【发布时间】:2017-06-27 19:59:36
【问题描述】:
所以在 Python 3 中,我可以使用 object().__eq__。我目前将其用作可映射函数,相当于lambda x: x is object()。
我将它用作哨兵(因为None 与没有参数的含义不同)。
>>> import sys
>>> print(sys.version)
3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]
>>> object.__eq__
<slot wrapper '__eq__' of 'object' objects>
>>> object().__eq__
<method-wrapper '__eq__' of object object at 0x000002CC4E569120>
但在 Python 2 中,这不起作用:
>>> import sys
>>> print sys.version
2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)]
>>> object.__eq__
<method-wrapper '__eq__' of type object at 0x0000000054AA35C0>
>>> object().__eq__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__eq__'
>>> dir(object)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
为什么没有这个功能?以及如何模拟它(与 Python 2 兼容)
$ python3 -m timeit "sentinel = object(); tests = [sentinel] * 100 + [None] * 100" "list(filter(sentinel.__eq__, tests))"
100000 loops, best of 3: 8.8 usec per loop
$ python3 -m timeit "sentinel = object(); tests = [sentinel] * 100 + [None] * 100; exec('def is_sentinel(x): return sentinel is x', locals(), globals())" "list(filter(is_sentinel, tests))"
10000 loops, best of 3: 29.1 usec per loop
【问题讨论】:
-
这正是你不应该使用
__dunder__这样的方法的原因。使用import operator; operator.eq -
或者实际使用
lambda thing: thing is sentinel;平等不一定是身份。 -
@jonrsharpe 我使用的是
s = object()。为此,我认为平等被定义为身份。 -
@Artyer 但语义不同;身份让读者更清楚什么是重要的,就像你应该测试
is None一样。 -
@Artyer 这是一个有趣的奥秘。我认为这与旧式和新式类之间的区别有关,这在 Python 3 中不存在。在 Python 2 中,您在
object上看到的__eq__方法似乎继承自type,而在 Python 3 中,object有它自己的__eq__方法,它没有被继承。无论如何,您应该使用operator模块来处理这些事情。在 Python 2 的情况下,object实例没有__eq__,因为object.__eq__属于类对象,而不是实例。即,它继承自元类type。
标签: python python-3.x compatibility python-2.x