Python 自省函数 getattr()
getattr() 这个函数最主要的作用是可以通过字符串获取方法实例
python 里面跟 getattr 相关的有 hasattr, setattr, delattr,下面通过一个示例来具体说明它们的用法,我们定义了一个 example 的类,下面的示例都将使用到它
class example:
    def __init__(self):
        self.name = 'hello'
    def greet(self):
        print self.name
e = example()
hasattr(object, name)
判断 object 是否有 name 这个属性,如果有则返回 True,否则返回 False
>>> hasattr(e, 'name')
True
>>> hasattr(e, 'greet')
True
>>> hasattr(e, 'greet1')
False
setattr(object, name, default)
给 object 添加一个新的属性 name 并赋值为 default
>>> hasattr(e, 'hello')
False
>>> setattr(e, 'hello', 'hello')
>>> hasattr(e, 'hello')
True
>>> e.hello
'hello'
delattr(object, name)
删除 object 的属性 name
>>> delattr(e, 'hello')
>>> hasattr(e, 'hello')
False
getattr(object, name[, default])
如果 object 存在 name 属性(方法)则返回 name 的值(方法地址)否则返回 default 值,如果 name 不存在且没有 default,将会抛出一个 AttributeError 的异常
>>> getattr(e, 'hello', 1)
1
>>> getattr(e, 'hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: example instance has no attribute 'hello'
getattr(object, name) 相当于 object.name,只不过这里可以把 name 作为一个变量去处理,你可以给它传递不同的值以实现不同功能的调用。
例:一个模块支持 html、text、xml 等格式的打印,根据传入的 format 参数的不同,调用不同的函数以不同格式的输出(下面的代码只是一个示例,那个模块并不真正存在,那只是我们假设它有格式化输出的功能)
import statsout
def output(data, format="text"):                           
    output_function = getattr(statsout, "output_%s" % format) 
    return output_function(data)
如果 getattr(object, name) 返回的是 object 的一个方法的话,你可以直接执行这个方法
>>> getattr(e, 'greet')()
hello
# 上面的代码相当于下面的这种形式,只是上面的形式写起来简单一点
>>> func = getattr(e, 'greet')
>>> func()
hello
# 本质都是
>>> e.greet()
hello
当然,如果那个方法接受参数的话,你也可以直接传递进去
>>> import operator
>>> getattr(operator, 'lt')(1, 2)
True
# 上面的代码相当于
>>> func = getattr(operator, 'lt')
# 也就是 operator.lt,这个方法接受两个参数,它的功能是比较第一个是否小于第二个参数
>>> func(1, 2)  # operator.lt(1, 2)
True
                    
                
                
            
        
浙公网安备 33010602011771号