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()