当您有一个任意的对象(也许是一个作为参数传递给函数的对象)时,可能希望知道一些关于该对象的情况。如希望python告诉我们:
1 对象的名称是什么?
2 这是哪种类型的对象?
3 对象知道些什么?
4 对象能做些什么?
5 对象的父对象是谁?
Python的自省机制,就是告诉我们这些问题的答案是什么。内置了很多模块:type(),dir(),getattr(),hasattr(),setattr(),isinstance()等。
dir()
Python 提供了一种方法,可以使用内置的 dir() 函数来检查模块(以及其它对象)的内容。
dir() 函数可能是 Python 自省机制中最著名的部分了。它返回传递给它的任何对象的属性名称经过排序的列表。如果不指定对象,则 dir() 返回当前作用域中的名称。让我们将 dir() 函数应用于 keyword 模块,并观察它揭示了什么:
1 2 3
| >>> import keyword >>> dir(keyword) ['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'iskeyword', 'kwlist', 'main']
|
type()
type() 函数有助于我们确定对象是字符串还是整数,或是其它类型的对象。它通过返回类型对象来做到这一点,可以将这个类型对象与 types 模块中定义的类型相比较:
1 2 3 4 5 6 7 8
| >>> type(42) <type 'int'> >>> type([]) <type 'list'> >>> type({}) <type 'dict'> >>> type(dir) <type 'builtin_function_or_method'>
|
getattr()
获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,可以在后面添加一对括号。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| >>> class test(): ... name="xiaohua" ... def run(self): ... return "HelloWord" ... >>> t=test() >>> getattr(t, "name") 'xiaohua' >>> getattr(t, "run") <bound method test.run of <__main__.test instance at 0x0269C878>> >>> getattr(t, "run")() 'HelloWord' >>> getattr(t, "age") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: test instance has no attribute 'age' >>> getattr(t, "age","18") '18' >>>
|
hasattr()
hasattr(object, name)
判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True,否则返回False。需要注意的是name要用括号括起来:
1 2 3 4 5 6 7 8 9 10 11
| >>> class test(): ... name="xiaohua" ... def run(self): ... return "HelloWord" ... >>> t=test() >>> hasattr(t, "name") True >>> hasattr(t, "run") True >>>
|
setattr()
给对象的属性赋值,若属性不存在,先创建再赋值。
1 2 3 4 5 6 7 8 9 10 11 12
| >>> class test(): ... name="xiaohua" ... def run(self): ... return "HelloWord" ... >>> t=test() >>> hasattr(t, "age") False >>> setattr(t, "age", "18") >>> hasattr(t, "age") True >>>
|
isinstance()
isinstance(object,type)
来判断一个对象是否是一个已知的类型。
1 2 3 4 5 6 7 8 9
| >>> a = "b" >>> isinstance(a,str) True >>> isinstance(a,int) False >>> isinstance(a,(int,list,float)) False >>> isinstance(a,(int,list,float,str)) True
|
v1.5.2