[Tutor] creating a method name on the fly

Python python at venix.com
Mon Aug 7 20:36:44 CEST 2006

On Mon, 2006-08-07 at 18:10 +0000, dave s wrote:
> I need to scan a long list of QT tickboxes in a dialog. I need to execute 
> pseudo code something like ...
> 		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).

key will be bound to each of the button attribute names in turn.  The
getattr call returns the button object.  NOTE: you no longer need to
specify self.  Then simply use the button object.

> where self.button.isChecked() becomes self.error_button.isChecked() ... 
> self.print_button.isChecked() ....  etc etc
> Can anyone tell me how to do this ? I have looked at apply but with no luck
> Thanks
> Dave
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
Lloyd Kvam
Venix Corp

More information about the Tutor mailing list