[Edu-sig] A better way?

Kirby Urner urnerk at qwest.net
Mon Nov 8 00:16:16 CET 2004

Just for exercise, one of my students assigned himself the task of making
instance attributes and methods accessible using square brackets instead of
dot notation.  This is the best solution I've been able to come up with so
far.  Suggestions?

 >>> class Test:
 	 def __init__(self):
	     self.attr1 = 1
	     self.attr2 = 2
	 def method1(self): print "Cough"
	 def method2(self): print "Chuckle"
	 def __getitem__(self, value):
	     return eval('self.'+value)

 >>> otest = Test()
 >>> otest['attr2']
 >>> otest['method1']()


More information about the Edu-sig mailing list