Python2与Python3双下划线方法

2024-05-23 20:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

所以在python3中,我可以使用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__']

为什么这个函数不存在?我如何模拟它(与python2兼容)

$ 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

Tags: ofimportnoneobjectisversionsysbit
1条回答
网友
1楼 · 发布于 2024-05-23 20:41:10

如果你想测试一个相等的函数

from functools import partial
from operator import eq

equals_thing = partial(eq, thing) # instead of thing.__eq__

这与thing.__eq__的行为稍有不同,因为它还为另一个参数提供了一个提供比较的机会,并且它不会返回NotImplemented。他说

不管你想要什么,用cd3代替:

from operator import is_

is_thing = partial(is_, thing)

如果您确实想要原始__eq__调用、NotImplemented和所有调用的python3行为,那么根据类型的不同,您可能需要手动重新实现它。对于object,那就是

lambda x: True if x is thing else NotImplemented

在python2中,并不是每个对象都定义__eq__,事实上,也不是每个对象都定义任何类型的相等比较,即使是旧式的__cmp__==的身份比较回退发生在任何对象的方法之外。他说

相关问题 更多 >