[英]Add __hash__ and __eq__ to imported type (tkinter DoubleVar) to put it in a dictionary
我從其他模塊導入了一些 class(在我的應用程序中,它是 tkinter DoubleVar),並希望將它們用作字典中的鍵。 但是 class 沒有定義__hash__
和__eq__
,所以它不起作用。
有沒有辦法添加這些方法? 我來自C#,那里有擴展方法,但我只是查了一下,並沒有找到在python中復制它的方法。
例子:
import tkinter as t
root = t.Tk()
var_A = t.DoubleVar(root)
var_A.set(10)
bounds = {} #I need to store the bounds for some optimization algorithm
bounds.update({var_A: [-10, 10]}) #Throws exception : TypeError: unhashable type: 'DoubleVar'
我可以以某種方式在導入的類型中實現 hash 功能嗎?
或者我是否必須編寫一個包裝器 class 允許我在實現__hash__
時訪問.get()
和.set()
方法?
編輯:我將嘗試解釋為什么我需要存儲邊界:我有一個具有適合功能的交互式 model。 用戶可以在不同的算法之間進行選擇。 我所有的舊算法(來自 scipy.optimize.minimize)都不需要邊界來工作,但是因為我想實現黑盒優化(使用這個 repo )並且算法需要邊界,所以我需要一些方法來獲取參數的邊界. 但是由於大約有 40 個不同的參數和超過 1500 行代碼,我一直在尋找一種方法來實現這一點而無需太多努力。 由於所有變量(即擬合參數)都存儲在 self 中,我想為邊界創建一種“查找表”。 你是對的,這不是做事的正確方法,但無論如何我現在找到了更好的解決方案。 謝謝
您可以將方法(包括__hash__
和類似方法)分配給現有類:
# a class without explicit __hash__
class A:
def __init__(self,i):
self.i = i
a1 = A(1)
print(hash(a1)) # default hash
# define a "free" function ...
def A_hash(self):
return hash(self.i)
# ... and "binds" it to class A
A.__hash__ = A_hash
a2 = A(1)
print(hash(a2)) # new it has user defined hash
編輯:使用最初不可散列的 object 和字典測試更新代碼:
# a class without explicit __hash__
class A(list):
def __init__(self,i):
self.i = i
a1 = A(1)
# print(hash(a1)) # would be TypeError: unhashable type: 'A'
# define a "free" function ...
def A_hash(self):
return hash(self.i)
# ... and "binds" it to class A
A.__hash__ = A_hash
a2 = A(1)
print(hash(a2)) # new it has user defined hash
d = {a2:1}
print(d)
我通過編寫實現__hash__
和__eq__
的包裝器 class 解決了我的問題。 class 還存儲了變量並提供了.get()
和.set()
所以我不需要更改所有代碼。
此外,我后來擺脫了將變量存儲在帶有邊界的字典中的想法,而只是將from_
和to
存儲在包裝器中,無論如何這更有意義
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.