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(object, name[, default])
getattr
with below example
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
student1 = Student("xyz", "6th", 7)
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
Similar Articles