This getattr()
function returns the value of the named attribute of the object.
getattr(object, name[, default])
Here,
>>> 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
.