Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ทำไมและอย่างไรฟังก์ชัน Python จึง Hashable

ออบเจ็กต์ที่ hashable ต้องมีค่า hash คงที่ตลอดชีวิต มีเมธอด __hash__() และเทียบเท่าได้ด้วย __eq__() หรือ __cmp__() ออบเจ็กต์ hashable ใช้เป็น dictionary key หรือสมาชิก set ได้

  • Built-in immutable objects (int, str, tuple) เป็น hashable
  • Mutable containers (list, dict) ไม่ hashable
  • User-defined class instances เป็น hashable โดยค่าเริ่มต้น (hash จาก id())

ฟังก์ชันและ lambda functions ก็เป็น hashable เพราะมี __hash__() และค่า hash คงที่

ตัวอย่าง

m = lambda x: 1
print(hash(m))      # 1265925722
print(id(m))        # 3074942372
print(m.__hash__()) # 1265925722

def f(): pass
print(type(f))      # 
print(f.__hash__()) # 1265925978
print(hash(f))      # 1265925978

ค่า hash ไม่จำเป็นต้องเท่ากับ id() แต่มาจากการคำนวณภายใน