How to use getattr in Python

This article explains how to use getattr in Python.

getattr returns the value of the named attribute of object. name must be a string. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised

getattr() Syntax


getattr(object, name[, default])


Lets understand getattr with below example
Create a Class with name Student


class Student:
    def __init__(self, name, grade, age):
        self.name = name
        self.grade = grade
        self.age = age

    def check_eligibility(self):
        if self.age > 8:
            msg = f"{self.name} eligible for {self.grade}"
        else:
            msg = f"{self.name} not eligible for {self.grade}"
        return msg


Create instance of Student class
        
        
student1 = Student("xyz", "6th", 7)
        
        
        
Get instance attributes with getattr
        
        
print(getattr(student1, "name"))

print(getattr(student1, "check_eligibility")())
   
# output

xyz
xyz not eligible for 6th
        
        

As shown in abobe code snippet getattr(student1, "name") is getting value of name attribute and getattr(student1, "check_eligibility")() is calling the method check_eligibility


Follow US on Twitter: