Python 中的 __hash__

Python中可哈希对象必须具备不变的hash值和eq()方法。不可变对象如元组和frozenset默认可哈希,而可变对象如列表和字典则不可。默认情况下,用户自定义类实例也是可哈希的,hash值基于id()。__hash__返回对象的唯一标识,而__eq__用于比较相等性。hash()函数确保同一解释器内相同字符串的hash值一致。
摘要由CSDN通过智能技术生成
官方文档对 可哈希的解释:hashable

An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() method). Hashable objects which compare equal must have the same hash value.
Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().


若对象在其生命周期内保持不变,而且能与其他对象相比较,那么这个对象是可哈希的。

通过__hash__返回一个int值,用来标记这个对象。对于类而言,如果没有实现 __eq__ 和 __hash__ 函数,那么会自动继承object.__hash__

   def __hash__(self):
        return hash(id(self))
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return hash(id(self))==hash(id(other))
        
Python,`__hash__()`是一个特殊方法(也称为魔术方法),用于定义对象的哈希值。哈希值是一个唯一的整数,用于在集合(如字典、集合)快速查找和比较对象。 当我们在自定义类没有定义`__hash__()`方法时,默认情况下,对象的哈希值是根据对象的内存地址计算的,即`id(obj)`。这意味着相同的对象可能具有不同的哈希值,因为它们在内存具有不同的地址。 如果我们想要自定义一个类的哈希值,可以在类实现`__hash__()`方法。这个方法应该返回一个整数,用于表示对象的哈希值。 下面是一个简单的示例,展示了自定义类`__hash__()`方法的使用: ```python class Student: def __init__(self, name, age): self.name = name self.age = age def __hash__(self): # 自定义哈希值为年龄的平方 return self.age ** 2 student1 = Student("Alice", 20) student2 = Student("Bob", 25) print(hash(student1)) # 输出:400 print(hash(student2)) # 输出:625 ``` 在上述示例,我们定义了一个`Student`类,并在其实现了`__hash__()`方法,计算哈希值为年龄的平方。通过调用`hash()`函数,我们可以获取对象的哈希值并进行打印。 需要注意的是,如果一个类定义了`__hash__()`方法,那么它也必须定义`__eq__()`方法,用于对象的相等性比较。这是因为哈希值只能用于快速查找,而对象的相等性比较需要通过`__eq__()`方法来确定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值