How do I use getattr and setattr properly in Python? [closed]

The second argument to getattr and setattr are strings that name the attribute you want. That is, getattr(name, "expected_grade"). Using a variable as the second argument means that the value of the variable is used as the name. Generally, though, there is no real difference between name.expected_grade and getattr(name, 'expected_grade'), although you can supply getattr an optional third argument that is returned (instead of raising an AttributeError) if the named attribute does not exist.

There is nothing in your code to indicate that you need getattr or setattr; just use the dotted name syntax to access the attributes.

Leave a Comment