getattr()
Reads an object’s attribute by a name given as a string, optionally with a default value.
- Returns
- The attribute’s value, or
default.
Example
#class Student:
def __init__(self, name, points):
self.name = name
self.points = points
emma = Student("Emma", 250)
print(getattr(emma, "points"))
print(getattr(emma, "level", 1))
for field in ["name", "points"]:
print(field, "=", getattr(emma, field))Definition and usage
#The getattr(object, "name") function works like object.name, but you give the attribute name as a string. That lets you pick the attribute only while the program is running, for example based on data from a file, settings, or a command typed by the user.
When the attribute does not exist, getattr() raises AttributeError. With a third argument, it returns a default value instead, which is handy for optional fields. You can read a method the same way: getattr(object, "save") returns the method, which you then call with parentheses.
Related functions are hasattr() (whether the attribute exists), setattr() (setting an attribute by name), and delattr() (removing an attribute). Don't use them where a plain dot or a dictionary is enough: code built on names stored in strings is harder to read, and the editor won't catch typos in it.
Syntax
#getattr(object, name)
getattr(object, name, default)Parameters
#object
any object
The object you read the attribute from. It can also be a class or a module.name
str
The name of the attribute or method.default
optional
The value returned when the attribute does not exist. Without it,AttributeErroris raised.
More examples
#class Robot:
def forward(self):
return "Moving forward"
def left(self):
return "Turning left"
robot = Robot()
for command in ["forward", "left", "jump"]:
action = getattr(robot, command, None)
print(action() if action else f"Unknown command: {command}")class Settings:
pass
settings = Settings()
for key, value in {"theme": "dark", "lang": "en"}.items():
setattr(settings, key, value)
print(settings.theme, settings.lang)
try:
getattr(settings, "font")
except AttributeError as error:
print(error)Good practices
#- Reach for
getattr()only when the attribute name is really known only while the program runs. Otherwise writeobject.attribute. - When a method name comes from the user, check it against a list of allowed commands, so a method you didn't anticipate can't be called.
- The function also works with modules:
getattr(math, "sqrt")(16)returns4.0.
Related entries
#- hasattr()Checks whether an object has an attribute or method with the given name. Returns True or False.
- dir()Returns a list of the names of an object’s attributes and methods.
- classDefines a class: a template for objects that combines data with the functions that act on it.
- selfThe first parameter of a method: the object the method was called on. It gives access to that object’s attributes and other methods.
- dict.get()Returns the value for a key, or a default value when the key is not in the dictionary.
Spotted a mistake or missing an example? Write to us.