【问题标题】:Why can I not assign `cls.__hash__ = id`?为什么我不能分配`cls.__hash__ = id`?
【发布时间】:2020-06-05 10:24:36
【问题描述】:

我希望这能工作(在 Python 3.6 中),

class A:
    __hash__ = id
A().__hash__()

但我明白了

TypeError: id() takes exactly one argument (0 given)

令人惊讶的是,

def my_id(self):
    return id(self)
class A:
    __hash__ = my_id
A().__hash__()

按预期工作。

【问题讨论】:

  • 不仅仅是__hash__。用普通方法你会得到同样的结果。我认为id 作为一个内置函数,并不完全遵循与用 Python 编写的函数相同的规则。

标签: python class attributes


【解决方案1】:

idbuiltin_function_or_method 类型(它是内置在运行时的函数 - ),出于实际原因(主要是优化),它没有像 python 函数那样实现 descriptor 协议,所以 @987654324 @ 解析为 id 函数本身,而不是包裹函数的 method 对象。

您将观察到大多数内置函数 FWIW 的相同行为:

>>> type(len)
<class 'builtin_function_or_method'>
>>> len.__get__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '__get__'
>>> 
>>> type(all)
<class 'builtin_function_or_method'>
>>> all.__get__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '__get__'
>>> type(abs)
<class 'builtin_function_or_method'>
>>> abs.__get__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '__get__'
>>> type(isinstance)
<class 'builtin_function_or_method'>
>>> isinstance.__get__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute '__get__'

等等……

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多