Dynamic attributes
Miki Tebeka
mtebeka at iil.intel.com
Thu Jan 18 08:59:30 EST 2001
Hello All,
Is there an "official" way to do the following?
class _setter:
def __init__(self, dict, key):
self.__dict = dict
self.__key = key
def __call__(self, value):
self.__dict[self.__key] = value
class _getter:
def __init__(self, dict, key):
self.__dict = dict
self.__key = key
def __call__(self):
return self.__dict[self.__key]
class DynAttribs:
def __init__(self):
self.__dict = {}
def addAttrib(self, attrib, value = None):
try: # check if we were initialized
self.__dict
except:
DynAttribs.__init__(self)
key = '__da%s' % attrib
self.__dict[key] = value
self.__dict__[attrib] = _getter(self.__dict, key)
self.__dict__['set%s' % attrib] = _setter(self.__dict, key)
>>> class XY(common.DynAttribs):
... def __init__(self, x, y):
... self.addAttrib('x', x)
... self.addAttrib('y', y)
...
>>> xy = XY(1,2)
>>> xy.x()
1
>>> xy.setx(100)
>>> xy.x()
100
Of course, you can add variant checks when assigning, but this is the
general idea.
Bye.
------------------------------------------------------------------------------
Smile, damn it, smile.
lambda msg: {
'name' : 'Miki Tebeka',
'email' : 'tebeka at lycosmail.com',
'homepage' : 'www.tebeka.freeservers.com',
'quote' : "I don't suffer from insanity, I enjoy every minute of it."
}[msg]
More information about the Python-list
mailing list