Python 检测成员函数、成员变量是否存在的方法

by Liu Yue/2013-07-18
如下为测试用例:

 # 定义一个类
>>> class A:
...     def __init__(self):
...             self.name = 'sunyi'
...     def fun1(self):
...             print "fun1"
...
# 创建对象a
>>> a = A()
# 检测是否存在属性 name
>>> hasattr(a,"name")
True
>>> hasattr(a,"age")
False
# 检测是否存在函数 fun1
>>> hasattr(a,"fun1")
True
>>> hasattr(a,"fun2")
False
#判断fun1是否为一个函数,如果是一个函数,返回True
>>> callable(getattr(a,"fun1"))
True
#判断fun1是否为一个函数,如果不是一个函数,返回False
>>> callable(getattr(a,"name"))
False
#判断fun2是否为一个函数,如果没有定义,则抛出异常
>>> callable(getattr(a,"fun2"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: A instance has no attribute 'fun2'
#直接调用fun1函数
>>> getattr(a,"fun1")()
fun1