[Tutor] creating a method name on the fly

wesley chun wescpy at gmail.com
Mon Aug 7 22:17:15 CEST 2006


> >               list = ['error_button',  'print_button' ... etc  ]
> >               for key in list:
> >                       button= list[key]
> >                       print button, self.button.isChecked()
> >
> list = ['error_button',  'print_button' ... etc  ]
>         for key in list:
>                         button= getattr(self, key)
>                         print button, button.isChecked()
>
> You can't use a string directly in an object reference, so self.key and
> self.button will not work.  You want to use the value in the string to
> look up an attribute.  The getattr function supports that ability.  (See
> also setattr and hasattr).

dave,

lloyd's suggestion is the way one "turns a string into an object," by
using getattr(). you are basically saying, i want to look up the
"printButton" attribute of self, and if it exists, give that object
back to me (as 'button').  then when you access button, you are really
manipulating self.printButton directly.

also, calling "print button" is only going to give you either the
object reference, i.e., "<object ... at ...>," not extremely useful
unless you've defined your __str__ special method.

the only other suggestion i'd give here is to not use "list" as a
variable name. that is the name of a Python data type and its
corresponding factory function, and by overriding it, you're
effectively "shadowing" it, so you can't use "list()" to make a list
anymore, and it also breaks typechecking with isintance().

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list