What is “getattr()” in Python?

GOAL

To understand getattr() function in python.

getattr(Object, name [, default])

Return the value of the named attribute of objectname must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Python document > library > functions

What will happen

The following is sample code with Dog class and getattr().

class Dog():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def sit(self):
        self.tired = False
        print("sit down")
    def bark(self, count):
        self.tired = True
        for i in range(count):
            print("bow wow")

dog1 = Dog("Poppy", 3)
val1 = getattr(dog1, "name")
val2 = getattr(dog1, "age")
val3 = getattr(dog1, "tired", "unknown")
val4 = getattr(dog1, "sit")()
val5 = getattr(dog1, "bark")(2)
val6 = getattr(dog1, "sit")
val7 = getattr(dog1, "bark")
val8 = getattr(dog1, "tired", "unknown")

Get attribute

# val1 = getattr(dog1, "name")
print(val1)
>> Poppy
# val2 = getattr(dog1, "age")
print(val2)
>> 3

Get default value

# val3 = getattr(dog1, "tired", "unknown")
print(val3)
>> unknown

Execute function

# val4 = getattr(dog1, "sit")()
print(val4)
>> None
# val5 = getattr(dog1, "bark")(2)
print(val5)
>> None

Get function

# val6 = getattr(dog1, "sit")
print(val6)
>> <bound method Dog.sit of <__main__.Dog object at 0x7f192a93f1d0>>
val6()
>> sit down
# val7 = getattr(dog1, "bark")
print(val7)
>> <bound method Dog.bark of <__main__.Dog object at 0x7fb2169ae1d0>>
val7(3)
>> bow wow
>> bow wow
>> bow wow

After Executing function

# val8 = getattr(dog1, "tired", "unknown")
print(val8)
>> True

getattr(dog1, sit)() and getattr(dog1, bark)(2) changed internal variable “tired”.