Dynamically Defined Functions in Classes?
Mark Pilgrim
f8dy at my-deja.com
Wed Jan 31 12:59:00 EST 2001
In article <mailman.980958702.3721.python-list at python.org>,
purp at wildbrain.com wrote:
> I have an application in which I wish to treat the members of a
> dictionary as attributes; that is, I want to use set-and-get functions
> to access them.
Sounds like you want a UserDict, which is a class that acts like a
dictionary.
from UserDict import UserDict
defaultFoo = {'joe' : 'cool', 'frank' : 'lee', 'ron' : 'dell'}
class Bar(UserDict):
def __init__(self):
UserDict.__init__(self, defaultFoo)
>>> b = Bar()
>>> b
{'ron': 'dell', 'joe': 'cool', 'frank': 'lee'}
>>> b["joe"]
'cool'
>>> b["mark"] = "pilgrim"
>>> b
{'mark': 'pilgrim', 'ron': 'dell', 'joe': 'cool', 'frank': 'lee'}
If you need to customize the getting and setting of attributes, you can
use the special methods __getitem__ and __setitem__ in your Bar class.
More on special methods in UserDict and its descendants:
http://diveintopython.org/fileinfo_specialmethods.html
http://python.org/doc/current/ref/sequence-types.html
-M
--
You're smart; why haven't you learned Python yet?
http://diveintopython.org/
Sent via Deja.com
http://www.deja.com/
More information about the Python-list
mailing list