SoFunction
Updated on 2024-11-10

Introduction and examples of built-in function getattr in python

In the official python documentation: getattr() is explained as follows:

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to . If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Returns the value of the object based on the name of the attribute. If "name" is the name of a property of the object, then the value of the corresponding property is returned.

'# -*- coding: utf-8 -*-'

__author__ = 'lucas'

class attrtest(object):

  def __init__(self):
    pass

  def trygetattr0(self):
     = 'lucas'
    print 
    #equals to 
    print getattr(self,'name')

  def attribute1(self,para1):
    print 'attribute1 called and '+ para1+' is passed in as a parameter'

  def trygetattr(self):
    fun = getattr(self,'attribute1')
    print type(fun)
    fun('crown')

if __name__=='__main__':
  test = attrtest()
  print 'getattr(self,\'name\') equals to  '
  test.trygetattr0()
  print 'attribute1 is indirectly called by fun()'
  ()
  print 'attrribute1 is directly called'
  test.attribute1('tomato')

The result of this code execution is:

getattr(self,'name') equals to  
lucas
lucas
attribute1 is indirectly called by fun()
<type 'instancemethod'>
attribute1 called and crown is passed in as a parameter
attrribute1 is directly called
attribute1 called and tomato is passed in as a parameter

Process finished with exit code 0

The first function tryattribute0() is very well understood, just as the definition says. The second function tryattribute1() is a little puzzling. In fact, the principle is not complicated, we see the type of fun is instancemethod, here you can think: for the function, getattr () return value is a pointer, pointer assigned to the variable that accepts it, and later call this variable is the same as calling the function pointed to by the variable.

We know the principle, so what does getattr do?

Are you familiar with reflection in java or c#? One of the important things that reflection does is delayed loading so that it can be decoupled, which allows the system to run more efficiently. As a dynamic language, python is obviously much more powerful in this regard.

getattr() is the building block for implementing python reflection. Combined with other methods like setattr(), dir(), etc., we can do a lot of interesting things.

Let's look at the following scenario:

1. I need to dynamically add methods in a class that are available in other classes:

# If class A has the following method:
def addnewattributesfromotherclass(self,class_name):
    func_names = dir(class_name)
    for func_name in func_names:
      if not func_name.startswith('_'):
        new_func = getattr(class_name,func_name)
        self.__setattr__(func_name,new_func())

We just need to:

a = A()

b = B()

(b)

This way a can call the 'non-private' method in B.