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 的响应):我试图通过执行以下操作调用42分配的值e["alpha"]

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
4

1 回答 1

5

定义__setitem__();看这里。也有对应__getitem__()的。

举个例子:

class Example(object):
    # define which names can be assigned using [...] syntax
    validkeys = set("alpha beta gamma".split())

    # assign valid names as attributes on our object
    def __setitem__(self, key, value):
        if key in self.validkeys:
            setattr(self, key, value)
        else:
            raise KeyError("Key must be one of %s", ", ".join(self.validkeys))

e = Example()
e["alpha"] = 42
print(e.alpha)   # prints 42

Check the full documentation for emulating dictionaries and other built-in types at: http://docs.python.org/reference/datamodel.html

于 2012-04-20T22:36:08.887 回答