Python: using getattr for properties and methods

Photo by Émile Perron on Unsplash

Using getattr

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)
adrienne = Person("Adrienne", "Domingus")
>>> adrienne.first_name
'Adrienne'
>>> getattr(adrienne, ‘first_name’)
‘Adrienne’
>>> getattr(adrienne, 'say_hello')
<bound method Person.say_hello of <Person object at 0x10640de50>>
>>> method = getattr(adrienne, 'say_hello')
>>> method("Someone else")
Hello, Someone else!

Putting it to work: generalizing method calls

if http_method == 'post':
requests.post(url, data=data)
elif http_method == 'put':
requests.put(url, data=data)
method = getattr(requests, http_method)
method(url, data=data)

Senior Software Engineer | www.adriennedomingus.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store