2.5 利用交互式提示符探索Python

无论是在IDLE中,还是在标准的交互式命令提示符下,都有一些便利的学习工具来探索Python。第一个工具是help()函数,它有两种模式。在命令提示符后输入help(),即可进入在线帮助系统,从中可以获得有关模块、关键字或主题的帮助。帮助系统内的提示符是help>,这时输入模块名称(如math或其他主题),就能查看相关的Python文档。

通常可以用更有针对性的方式来使用help(),这样会更为便捷。只要将类型或变量名称作为help()的参数,就可以马上显示其帮助文档:

>>> x=2
>>> help(x)
Help on int object:

class int(object)
  |  int(x=0) -> integer
  |  int(x, base=10) -> integer
  |
  |  Convert a number or string to an integer, or return 0 if no arguments
  |  are given. If x is a number, return x.__int__(). For floating point
  |  numbers, this truncates towards zero.
  |
  |  If x is not a number or if base is given, then x must be a string,
  |  bytes, or bytearray instance representing an integer literal in the...
(continues with the documentation for an int)

以这种方式使用help(),可以很方便地查看某个方法的确切语法和对象的行为。

help()函数是pydoc库的一部分,它在访问Python库内文档时有若干个参数可供选用。因为所有Python安装完成后都会自带完整的文档,即使不能上网,全部官方文档也都唾手可得。有关访问Python文档的更多信息,参见附录A。

另一个有用的函数是dir(),它列出了特定名称空间中的对象。在没有给出参数时,它会列出当前的全局变量,但它也可以列出某个模块中的全部对象,甚至某个类型的全部对象:

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__',
      '__package__', '__spec__', 'x']
>>> dir(int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__',
      '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__',
      '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__',
      '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__',
      '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__',
      '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__',
      '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__',
      '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__',
      '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__',
      '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__',
      '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes',
      'imag', 'numerator', 'real', 'to_bytes']
>>>

dir()函数在查找方法和数据的定义时十分有用,可以一眼就看到属于某个对象或模块的全部成员。在调试代码的时候也很有用,因为在什么地方定义了什么都一目了然。

与dir()函数不同,globals()和locals()函数会显示与对象关联的值。在目前情况下,这两个函数会返回相同的结果,所以这里只给出globals()的输出结果:

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class
      '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},
      '__builtins__': <module 'builtins' (built-in)>, 'x': 2}

与dir()函数不同,globals()和locals()显示的都是与对象相关的值。在第10章中这两个函数将会更频繁地出现。好了,这足以说明,有多种方法可以查看Python会话内的当前状态。