Dynamic assignment of instance variables ( was: tuple driven processing )

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Thu, 9 Dec 1993 16:32:10 -0500

Using setattr to initialize a list of instance variables is definitely
better and less implementation dependant than manipulating the
instances __dict__ structure ( self.__dict__[key] = value ),
( which is less implementation dependant, but STILL nicer that
using eval: "eval( repr(thing)+'.'+key+ '=' + repr(value) )" )
but, for external access to instance variables, it's even better to
map __[get/set]item__() to [get/set]attr(). Instance variables
can then be accesses as either "thing.ivar" or indirectly as
"key='ivar'; thing[key]" .

In fact, I think this is useful enough, that I would propose that
it be made the default method for classes where __getitem__ or
__setitem__ are NOT defined.

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics

#
# example: initializing from a list of instance variables, and
# indirect reference to instance variables via get/set-item.
#

_default_instance_vars = [ ( 'abc', 'ABC' ), ( 'digits', '0123456789' ),
( 'me', None ), ( 'one', 1 ), ( 'two', 2 ), ( 'three', 3 ) ]

class Thing:
def __init__( self, *things ):
self.init( _default_instance_vars )
if things:
apply( self.init, things )
def init( self, things ):
for x in things:
self[x[0]] = x[1]
def __getitem__( self, item ):
return getattr( self, item )
def __setitem__( self, item, value ):
setattr( self, item, value )
def listvars( self ):
for k in dir(self):
print (k, self[k])

a = Thing( [( 'test', 'TESTING: 1,2,3...' ) ])
print 'print a.test: ', a.test
print 'print a[\'test\']: ', a['test']
print 'a.listvars()'
a.listvars()