YouTip LogoYouTip

Python Func Getattr

# Python2.x Python getattr() Function [![Image 3: Python Built-in Functions](#) Python Built-in Functions](#) * * * ## Description The **getattr()** function is used to return the value of an object's attribute. ## Syntax getattr syntax: getattr(object, name[, default]) ## Parameters * object -- The object. * name -- A string, the name of the object attribute. * default -- The default value to return. If this parameter is not provided and the attribute does not exist, an AttributeError will be raised. ## Return Value Returns the value of the object's attribute. ## Example The following example demonstrates the usage of getattr: >>>class A(object): ... bar = 1 ... >>>a = A()>>>getattr(a, 'bar')# Get attribute bar value 1>>>getattr(a, 'bar2')# Attribute bar2 does not exist, raises exception Traceback(most recent call last): File"", line 1, inAttributeError: 'A'object has no attribute'bar2'>>>getattr(a, 'bar2', 3)# Attribute bar2 does not exist, but default value 3 is set>>> [![Image 4: Python Built-in Functions](#) Python Built-in Functions](#)
← Python Func XrangePython Func Frozenset β†’