Dynamic properties

Jeremy Bowers jerf at jerf.org
Fri Jan 21 08:46:18 EST 2005


On Fri, 21 Jan 2005 23:27:28 +0800, Craig Ringer wrote:
> 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.
>>> 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]
... 
>>> a = {'LV1': .5, 'LV10': 5, 'LV100': 50}
>>> d = DictWrap(a)
>>> d.LV1
0.5
>>> d.LV1 = "Hello!"
>>> d.LV5 = 2.5
>>> d.__dict__
{'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV100': 50, 'LV1': 'Hello!'}}
>>> del d.LV100
>>> d.__dict__
{'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV1': 'Hello!'}}
>>> 





More information about the Python-list mailing list