Member-only story
Python: using getattr for properties and methods
Using getattr
Before we jump into how getattr can be a useful tool for DRYing up our code, lets cover how it works (docs here)! In short, it takes an object and a string version of a property name, and returns the value of that property, if it exists on an object. It can optionally take a default value to return if the attribute can’t be found on the object, and otherwise will return an AttributeError.
Okay, let’s look at an example, using a bare-bones class. Given the Person class as defined below:
class Person(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name def say_hello(name):
print "Hello, {}!".format(name)
Okay, let’s get an instance of a Person:
adrienne = Person("Adrienne", "Domingus")Once I’ve been instantiated, we can access my first_name (and last_name) attribute using the more familiar dot notation, but we can also get it using getattr, with the same result:
>>> adrienne.first_name
'Adrienne'
>>> getattr(adrienne, ‘first_name’)
‘Adrienne’This makes sense, because the _name attributes are…attributes. But now for the fun part: did you know that…
