What is getattr() exactly and how do I use it?

前端 未结 14 1808
孤独总比滥情好
孤独总比滥情好 2020-11-22 09:04

I\'ve recently read about the getattr() function. The problem is that I still can\'t grasp the idea of its usage. The only thing I understand about getattr() is

14条回答
  •  时光取名叫无心
    2020-11-22 09:38

    Objects in Python can have attributes -- data attributes and functions to work with those (methods). Actually, every object has built-in 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 attr_name.

    if

    attr_name = 'gender'
    

    then, instead of writing

    gender = person.gender
    

    you can write

    gender = getattr(person, attr_name)
    

    Some practice:

    Python 3.4.0 (default, Apr 11 2014, 13:05:11)
    
    >>> 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
    

    getattr will raise AttributeError if attribute with the given name does not exist in the object:

    >>> getattr(person, 'age')
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'Person' object has no attribute 'age'
    

    But you can pass a default value as the third argument, which will be returned if such attribute does not exist:

    >>> getattr(person, 'age', 0)
    0
    

    You can use getattr along with dir to iterate over all attribute names and get their values:

    >>> dir(1000)
    ['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
    
    >>> obj = 1000
    >>> for attr_name in dir(obj):
    ...     attr_value = getattr(obj, attr_name)
    ...     print(attr_name, attr_value, callable(attr_value))
    ... 
    __abs__  True
    ...
    bit_length  True
    ...
    
    >>> getattr(1000, 'bit_length')()
    10
    

    A practical use for this would be to find all methods whose names start with test and call them.

    Similar to getattr there is setattr which allows you to set an attribute of an object having its name:

    >>> setattr(person, 'name', 'Andrew')
    >>> person.name  # accessing instance attribute
    'Andrew'
    >>> Person.name  # accessing class attribute
    'Victor'
    >>>
    

提交回复
热议问题