[Edu-sig] Re: A better way?

Scott David Daniels Scott.Daniels at Acm.Org
Mon Nov 8 00:38:58 CET 2004


Kirby Urner wrote:
> 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']
>  2
>  >>> otest['method1']()
>  Cough
> 
> Kirby

What's wrong with:

 >>> 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 getattr(self, value)

 >>> Test()['attr1']
1
 >>> Test()['attr2']
2
 >>> Test()['method1']()
Cough
 >>> Test()['method2']()
Chuckle

-- 
-- Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Edu-sig mailing list