The following code creates a simple gui using the Tkinter module.
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()
Now look at the following bit of code:
button1["text"]= "Hello, World!"
This syntax looks the same as assigning a value to a dictionary key.
How do you define the possibility for this behavior for user defined objects?
Could you please show with an example such as:
class Example(object):
def __init__(self, length = 1, width= 2):
self.length = length
self.width = width
Edit 1(response to kindall and jsbueno):
I’m trying to call the value 42 assigned to e["alpha"] by doing:
print e["alpha"]
To your code I added:
def __getitem__(self, key, value):
if key in self.validkeys:
getattr(self, key, value)
else:
raise KeyError
But I still get the ‘Example’ is not subscriptable TypeError.
Edit 2
def __getitem__(self, key):
if key in self.validkeys:
return getattr(self, key)
else:
raise KeyError
Define
__setitem__(); see here. There is a corresponding__getitem__()as well.As for an example:
Check the full documentation for emulating dictionaries and other built-in types at:
http://docs.python.org/reference/datamodel.html