J
Jeremy Bowers
The chances are that whatever you want to do with dynamically created
properties is better done with __getattr__ and __setattr__ instead.
Rather than post my own comment, I'd like to highlight this, emphasize it,
and underline it twice. The two other repliers I see were nice to explain
how to do what you were trying to do, but you probably shouldn't do it
that way.
class DictWrap(object):
def __init__(self, dictToWrap):
self.__dict__['dictToWrap'] = dictToWrap
def __getattr__(self, key):
return self.__dict__['dictToWrap'][key]
def __setattr__(self, key, value):
self.__dict__['dictToWrap'][key] = value
def __delattr__(self, key):
del self.__dict__['dictToWrap'][key]
Note the direct use of __dict__, which bypasses the *attr machinery.
This implements a "full" dict wrap; adjust as needed. Be sure to read
about *attr in the Python manual so you understand what they do. You can
do more in getattr if you want, but it doesn't sound like you want much
else.
Python 2.3.4 (#1, Oct 26 2004, 20:13:42)
[GCC 3.4.2 (Gentoo Linux 3.4.2-r2, ssp-3.4.1-1, pie-8.7.6.5)] on linux2
Type "help", "copyright", "credits" or "license" for more information..... def __init__(self, dictToWrap):
.... self.__dict__['dictToWrap'] = dictToWrap
.... def __getattr__(self, key):
.... return self.__dict__['dictToWrap'][key]
.... def __setattr__(self, key, value):
.... self.__dict__['dictToWrap'][key] = value
.... def __delattr__(self, key):
.... del self.__dict__['dictToWrap'][key]
....