【Intermediate Python】十四、对象自省

自省(instrospection),在计算机编程领域里,是指在运行时来判断一个对象的类型的能力。它是 Python 的强项之一。Python 中所有一切都是一个对象,而且我们可以仔细勘察那些对象。Python 还包含了许多内置函数和模块来帮助我们。

dir

在这个小节里我们会学习到 dir 以及它在自省方面如何给我们提供便利。

它是用于自省的最重要的函数之一。它返回一个列表,列出了一个对象所拥有的属性和方法。下面是一个例子:

my_list = [1, 2, 3]
dir(my_list)
# Output:
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

上面的自省给了我们一个列表对象的所有方法的名字。当你没法回忆起一个方法的名字,这会非常有帮助。如果我们运行 dir() 而不传入参数,那么它会返回当前作用域的所有名字。

type 和 id

type 函数返回一个对象的类型。举个例子:

print(type(''))
# Output: <class 'str'>

print(type([]))
# Output: <class 'list'>

print(type({}))
# Output: <class 'dict'>

print(type(dict))
# Output: <class 'type'>

print(type(3))
# Output: <class 'int'>

id() 函数返回任意不同种类对象的唯一 ID,举个例子:

name = "Yasoob"
print(id(name))
# Output: 2016016298224

inspect 模块

inspect 模块也提供了许多有用的函数,来获取活跃对象的信息。比方说,你可以查看一个对象的成员,只需运行:

import inspect
print(inspect.getmembers(str))
# Output: [('__add__', <slot wrapper '__add__' of 'str' objects>), ...

还有好多个其他方法也能有助于自省。如果你愿意,你可以去探索它们。