1
以下代碼使用Tkinter模塊創建一個簡單的gui。如何爲用戶定義的對象定義類似字典的值賦值?
import Tkinter
root = Tkinter.Tk()
myContainer1 = Tkinter.Frame(root)
myContainer1.pack()
button1 = Tkinter.Button(myContainer1)
button1["text"]= "Hello, World!"
button1["background"] = "green"
button1.pack()
root.mainloop()
現在看一下下面的代碼位:
button1["text"]= "Hello, World!"
這個語法看起來一樣的字典鍵分配一個值。 如何爲用戶定義的對象定義此行爲的可能性? 能否請你告訴用一個例子如:
class Example(object):
def __init__(self, length = 1, width= 2):
self.length = length
self.width = width
編輯1(響應kindall和jsbueno): 我試圖做調用分配給e["alpha"]
值42
:
print e["alpha"]
你的代碼我說:
def __getitem__(self, key, value):
if key in self.validkeys:
getattr(self, key, value)
else:
raise KeyError
但我仍然得到'示例'不是可自定義的TypeError。
編輯2
def __getitem__(self, key):
if key in self.validkeys:
return getattr(self, key)
else:
raise KeyError
謝謝!我試圖通過輸入'print e [「alpha」]'來調用值'42'。我通過定義'__getitem__'來定義它。但是我仍然得到一個TypeError。你能檢查我編輯過的原始回覆嗎? – Bentley4 2012-04-21 15:47:18
'__getitem __()'只有兩個參數,你需要三個參數。我相信這是問題所在。 – kindall 2012-04-22 00:23:27