Tuesday, September 30, 2008

getattr()

Python’s getattr function is used to fetch an attribute from an object, using a string object instead of an identifier to identify the attribute. In other words, the following two statements are equivalent:

value = obj.attribute
value = getattr(obj, "attribute")


The function takes an optional default value, which is used if the attribute doesn’t exist. The following example only calls the method if it exists:

func = getattr(obj, "method", None)
if func:
func(args)

http://effbot.org/zone/python-getattr.htm

No comments: