对象自省

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

dir

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

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

  1. my_list = [1, 2, 3]
  2. dir(my_list)
  3. # Output: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
  4. # '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
  5. # '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__',
  6. # '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
  7. # '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
  8. # '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
  9. # '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop',
  10. # 'remove', 'reverse', 'sort']

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

typeid

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

  1. print(type(''))
  2. # Output: <type 'str'>
  3. print(type([]))
  4. # Output: <type 'list'>
  5. print(type({}))
  6. # Output: <type 'dict'>
  7. print(type(dict))
  8. # Output: <type 'type'>
  9. print(type(3))
  10. # Output: <type 'int'>

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

  1. name = "Yasoob"
  2. print(id(name))
  3. # Output: 139972439030304

inspect 模块

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

  1. import inspect
  2. print(inspect.getmembers(str))
  3. # Output: [('__add__', <slot wrapper '__add__' of ... ...

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