Built-in getattr function

Thursday, May 30, 2013

 You can get a reference to a function without knowing its name until run-time, by using the getattr function.
 class Cls():  
   def getfood(self):  
     self.food = ['Cheese', 'Pizza', 'Burger', 'Hotdog', 'Pie', 'Fires']  
     return self.food  
 c = Cls()  
 print getattr(c, 'getfood')() 

The output of following code will be
 ['Cleese', 'Palin', 'Idle', 'Gilliam', 'Jones', 'Chapman']



Here are some more example of getattr function.


 >>> li = ["Apple", "orange", 'pineapple']  
 >>> li.pop  
 <built-in method pop of list object at 010DF884>  
 >>> getattr(li, "pop")  
 <built-in method pop of list object at 010DF884>  
 >>> getattr(li, "append")("berry")  
 >>> li  
 ["Apple", "orange", 'berry']  
 >>> getattr({}, "clear")  
 <built-in method clear of dictionary object at 00F113D4>  

No comments:

Post a Comment