Ruben
Ruben

Reputation: 233

Why should I ever use "getattr()"?

From my understanding, getattr(object, "method") is equivalent to object.method(). If this is true, what is the point of using getattr?

Upvotes: 7

Views: 3189

Answers (3)

plasmid0h
plasmid0h

Reputation: 206

Objects in Python can have attributes. For example you have an object person, that has several attributes: name, gender, etc. You access these attributes (be it methods or data objects) usually writing: person.name, person.gender, person.the_method(), etc.

But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called gender_attribute_name.

if

attr_name = 'gender'

then, instead of writing

gender = person.gender

you can write

gender = getattr(person, attr_name)

Some practice:

>>> class Person():
...     name = 'Victor'
...     def say(self, what):
...         print(self.name, what)
... 
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
>>> 

Upvotes: 6

Thomas Orozco
Thomas Orozco

Reputation: 55199

Usually when the name of the method is not known when you write the code:

def print_some_attr(obj, attr):
    print getattr(obj, attr)

Or when you want to write generic code that works on multiple attributes, while avoiding writing the same thing over and over:

for attr in ["attr1", "attr2", "attr3"]:
    print "%s is: %s" % (attr, getattr(obj, attr))

Upvotes: 3

Constantinius
Constantinius

Reputation: 35039

You can use getattr if you have the name of the attribute as a string. e.g:

attribute = "some_attribute"
getattr(object, attribute)

Also it is nice to use when you have a default value that you want to use when the attribute is not set:

getattr(object, attribute, "default")  # does not raise AttributeError

Upvotes: 8

Related Questions