正在调用\uUu hash_Uu()方法

2024-04-16 20:21:14 发布

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

我定义类MyClass()

import random
class MyClass():
    def __init__(self, value):
        self.value = value
    def __hash__(self):
        return random.randin(1, 10) 
x = MyClass() 

我知道,在我声明x = MyClass()之后,__init__是自动调用的。但是__hash__呢?它在没有被x.__hash__()显式调用的情况下工作吗?
每个以__开头的方法是自动调用的还是程序决定何时调用它们?
为了找到答案,我查阅了许多文件,但都没有成功。在

谢谢你的回答!在


Tags: 方法importself声明return定义initvalue
2条回答

来自Python文档:

Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. __hash__() should return an integer. The only required property is that objects which compare equal have the same hash value;

参考号:https://docs.python.org/3/reference/datamodel.html#object.__hash__

另外,请不要从\uuHash_Uu()返回随机数。在

否,__hash__不会自动调用。看看the documentation for this method

Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict.

因此,如果有人hash(x),将调用此方法。在

顺便说一句,返回一个随机数是个坏主意:

The only required property is that objects which compare equal have the same hash value

相关问题 更多 >