I have name of class in string like:
conf[0] = 'smtp_config'
and i want to run method like:
self.ui.smtp_config.setText("....")
How can i do this in python? :)
asked Feb 11, 2011 at 20:48
Rafał Kot
1,0843 gold badges16 silver badges26 bronze badges
2 Answers 2
Try getattr(self.ui,conf[0]).setText(...)
answered Feb 11, 2011 at 20:51
Alexander Gessler
46.9k7 gold badges87 silver badges124 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Daniel DiPaolo
+1 ...though a
hasattr call first is probably preferable :)Ben
Isn't hasattr roughly implemented by doing getattr and catching the exception anyway? Just call getattr. If the program can do something sensible if the attribute doesn't exist, catch the exception. If not, ignore it, and let the stack trace tell you about the bug when it turns out it's not there.
func = getattr(self.ui, conf[0])
func.setText("....")
answered Feb 11, 2011 at 20:51
ChristopheD
117k30 gold badges167 silver badges182 bronze badges
Comments
lang-py