[Edu-sig] A better way?

Laura Creighton lac at strakt.com
Mon Nov 8 06:00:24 CET 2004


In a message of Sun, 07 Nov 2004 15:16:16 PST, "Kirby Urner" writes:
>
>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 s
>o
>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
>

Is this what you want?

Python 2.3.4c1 (#2, May 13 2004, 21:46:36)
[GCC 3.3.3 (Debian 20040429)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
...      def __init__(self):
...              self.attr1 = 1
...              self.attr2 = 2
...      def method1(self): print "Cough"
...      def method2(self): print "Chuckle"
...      def __getitem__(self, method_name):
...              method = getattr(self, method_name, None)
...              if callable(method):
...                      method()
...              else:
...                      return method
...
>>> otest = Test()
>>> otest['attr2']
2
>>> otest['method1']
Cough
>>>

--------

Note method(*args, **kwargs), not shown here will work when your method wants arguments.

Good luck,  I am off to catch an airplane, back on Nov 28 or so, and probably not
answering mail ...

Laura



More information about the Edu-sig mailing list