What does getattr() function do in Python?


Python getattr()

The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

Syntax

The syntax of getattr() method is −

getattr(object, name[, default])

The getattr() method can take multiple parameters −

The getattr() method returns −

value of the named attribute of the given object

default, if no named attribute is found

AttributeError exception, if named attribute is not found and default is not defined

Example

class Male:
    age = 21
    name = "Abel"
x = Male()
print('The age is:', getattr(x, "age"))
print('The age is:', x.age)

Output

This gives the output

('The age is:', 21)
('The age is:', 21)

Updated on: 13-Jun-2020

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements