ScanSkill

getattr

This getattr() function returns the value of the named attribute of the object.

Syntax

getattr(object, name[, default])

Here,

  • object: Required. An object whose attribute is to be returned.
  • name: Required. Must be a string. If the named attribute does not exist, default is returned if used, otherwise, AttributeError is raised.
  • default: Optional. A value that will be returned if the name attribute does not exist.

Examples

>>> class Class1:
...     def __init__(self, x):
...         self.x = x
...
>>> f = Class1(10)
>>> getattr(f, 'x')
10
>>> f.x
10
>>> getattr(f, 'y', 'cloudy') 
'cloudy'

If named attribute doesnot exist

>>> class Class1:
...     def __init__(self, x):
...         self.x = x
...
>>> f = Class1(10)
>>> getattr(f, 'x')
10
>>> f.x
10
>>> # When default value is provided
>>> getattr(f, 'y', 'cloudy') 
'cloudy'

>>> # When default value is not provided
>>> getattr(f, 'y')
AttributeError: 'Class1' object has no attribute 'y'

Here, The named attribute y is not in the class Class1. So, it will return the default value if provided, Otherwise, it will throw an AttibuteError.