[Python学习笔记-001] 内置函数getattr()

时间:2022-03-01 09:38:29

如果某个实例foo有多个方法, 当对foo的每一个方法我们都需要使用try ... except ...进行包装的时候,内置函数getattr()可以用来精简代码。

1. getattr()的用法

# https://docs.python.org/2/library/functions.html#getattr

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 x.foobar. If
the named attribute does not exist, default is returned if provided, otherwise
AttributeError is raised.

简单来说,getattr()就是获取对象object的属性或者方法。如果获取对象的方法,则返回的是该方法的内存地址。那么,如需要运行这个方法,在后面添加一对括号即可。这跟使用函数指针是类似的。举个例子:

  • foo.py
 #!/usr/bin/python

 import sys

 class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age def get_name(self):
return self.name def get_age(self):
return self.age def set_name(self, name):
self.name = name def set_age(self, age):
self.age = age def main(argc, argv):
p = Person('Jack', 25)
print 'Name: %s, Age: %d' % (p.get_name(), p.get_age()) getattr(p, 'set_name')('Lily')
getattr(p, 'set_age')(36)
print 'Name: %s, Age: %d' % (getattr(p, 'get_name')(),
getattr(p, 'get_age')()) return 0 if __name__ == '__main__':
argv = sys.argv
argc = len(sys.argv)
sys.exit(main(argc, argv))
  • run foo.py
$ ./foo.py
Name: Jack, Age:
Name: Lily, Age:

在上面的例子中,

getattr(p, 'set_name')('Lily')

等同于

p.set_name('Lily')

2. 一个利用getattr()精简代码的例子

 import time

 class JenkinsProject(object):
def __get_job_prop(self, job, method, interval):
for i in range(self.retry_cnt):
try:
return getattr(job, method)()
except Exception as e:
time.sleep(interval) print("fail to %s after retry %d times" %
(method.replace('_', ' '), self.retry_cnt))
raise e def get_build_ids(self, job, interval=60):
return self.__get_job_prop(self, job, 'get_build_ids', interval) def get_last_build(self, job, interval=60):
return self.__get_job_prop(self, job, 'get_last_build', interval)