cymbalic reference?

Terry Reedy tjreedy at udel.edu
Wed Jan 16 00:23:38 EST 2013


On 1/15/2013 11:56 PM, rh wrote:
> I have this working and I am curious to know how others do same.
>
> class Abc(object):
>      def __init__(self):
>          pass
>      def good(self):
>          print "Abc good"
>      def better(self):
>          print "Abc better"
>
> urls = {'Abc':'http://example.com'}
> strings = ['good', 'better']
>
> for s in urls:
>      o = eval("%s()" % s)
>      for string in strings:
>          eval("o.%s()" % string)

for s in urls:
     o = globals()[s]()
     for string in strings:
         getattr(o,string)()

has same output. eval is seldom needed.
Of course, if you more sensibly use the class or an instance as key
urls = {Abc: 'http://example.com'}
urls = {Abc(): 'http://example.com'}
instead of the name, then o = s() or o = s directly.

> While I'm at it what magic could I use to print "the-class-I-am-in good"
> instead of hard-coding "Abc good"? I tried __class_ and self.__class__

self.__class__.__name__ or type(self).__name__)

-- 
Terry Jan Reedy




More information about the Python-list mailing list