getattr() function in python is sued to get the value of an object attribute and it return the default value if no attribute of that object is found.
Example for getattr() function in python
The reason of using getattr() function because it return the default value.Now let see the basic syntax : -
getattr(object_name, attribute_name[, default_value])
Example of getattr() function in python
this program will help you to teach about how to use the getattr() function in python
class Student: student_id="" student_name="" # initial constructor to set the values def __init__(self): self.student_id = "101" self.student_name = "Adam Lam" student = Student() # get attribute values by using getattr() function print('\ngetattr : name of the student is =', getattr(student, "student_name")) # but you could access this like this print('traditional: name of the student is =', student.student_name)
Why use getattr() function
- This function helps to get the object attribute value with the help of Name of that attr. or you can also manually set the input attribute name by console.
- This function also give the freedom for set the default value according to your need.
0 comments:
Post a Comment