Search code examples
pythongetattr

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?


Solution

  • 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
    >>>