4.3. 使用 typestrdir 和其他内置函数

Python 有一小组非常有用的内置函数。所有其他函数都被划分到模块中。这实际上是一个有意识的设计决定,是为了防止核心语言像其他脚本语言(咳咳,Visual Basic)那样臃肿。

4.3.1. type 函数

type 函数返回任意对象的數據类型。可能的类型列在 types 模块中。这对于可以处理多种数据类型的辅助函数很有用。

示例 4.5. 介绍 type

>>> type(1)           1
<type 'int'>
>>> li = []
>>> type(li)          2
<type 'list'>
>>> import odbchelper
>>> type(odbchelper)  3
<type 'module'>
>>> import types      4
>>> type(odbchelper) == types.ModuleType
True
1 type 接受任何东西——我的意思是任何东西——并返回其数据类型。整数、字符串、列表、字典、元组、函数、类、模块,甚至类型都是可以接受的。
2 type 可以接受一个变量并返回其数据类型。
3 type 也适用于模块。
4 您可以使用 types 模块中的常量来比较对象的类型。这就是 info 函数的作用,您很快就会看到。

4.3.2. str 函数

str 将数据强制转换为字符串。每种数据类型都可以强制转换为字符串。

示例 4.6. 介绍 str

>>> str(1)          1
'1'
>>> horsemen = ['war', 'pestilence', 'famine']
>>> horsemen
['war', 'pestilence', 'famine']
>>> horsemen.append('Powerbuilder')
>>> str(horsemen)   2
"['war', 'pestilence', 'famine', 'Powerbuilder']"
>>> str(odbchelper) 3
"<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>"
>>> str(None)       4
'None'
1 对于像整数这样的简单数据类型,您会期望 str 可以工作,因为几乎每种语言都有一个将整数转换为字符串的函数。
2 但是,str 适用于任何类型的任何对象。在这里,它适用于您已经一点一点构建的列表。
3 str 也适用于模块。请注意,模块的字符串表示形式包括模块在磁盘上的路径名,因此您的路径名将有所不同。
4 str 的一个微妙但重要的行为是它适用于 None,即 Python 的空值。它返回字符串 'None'。您将在 info 函数中利用这一点,您很快就会看到。

info 函数的核心是强大的 dir 函数。dir 返回任何对象的属性和方法的列表:模块、函数、字符串、列表、字典……几乎任何东西。

示例 4.7. 介绍 dir

>>> li = []
>>> dir(li)           1
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
>>> d = {}
>>> dir(d)            2
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values']
>>> import odbchelper
>>> dir(odbchelper)   3
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']
1 li 是一个列表,因此 dir(li) 返回列表所有方法的列表。请注意,返回的列表包含方法的名称作为字符串,而不是方法本身。
2 d 是一个字典,因此 dir(d) 返回字典方法名称的列表。其中至少有一个,keys,应该看起来很熟悉。
3 这就是它真正有趣的地方。odbchelper 是一个模块,因此 dir(odbchelper) 返回模块中定义的所有内容的列表,包括内置属性,如 __name____doc__,以及您定义的任何其他属性和方法。在这种情况下,odbchelper 只有一个用户定义的方法,即 第 2 章 中描述的 buildConnectionString 函数。

最后,callable 函数接受任何对象,如果该对象可以被调用,则返回 True,否则返回 False。可调用对象包括函数、类方法,甚至类本身。(下一章将详细介绍类。)

示例 4.8. 介绍 callable

>>> import string
>>> string.punctuation           1
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.join                  2
<function join at 00C55A7C>
>>> callable(string.punctuation) 3
False
>>> callable(string.join)        4
True
>>> print string.join.__doc__    5
join(list [,sep]) -> string

    Return a string composed of the words in list, with
    intervening occurrences of sep.  The default separator is a
    single space.

    (joinfields and join are synonymous)
1 string 模块中的函数已弃用(尽管许多人仍在使用 join 函数),但该模块包含许多有用的常量,例如 string.punctuation,其中包含所有标准标点符号。
2 string.join 是一个连接字符串列表的函数。
3 string.punctuation 不可调用;它是一个字符串。(字符串确实有可调用的方法,但字符串本身不可调用。)
4 string.join 可调用;它是一个接受两个参数的函数。
5 任何可调用对象都可以有一个 docstring。通过对对象的每个属性使用 callable 函数,您可以确定哪些属性是您关心的(方法、函数、类),哪些属性是您想忽略的(常量等),而无需事先了解该对象。

4.3.3. 内置函数

typestrdir 以及所有其他 Python 内置函数都被分组到一个名为 __builtin__ 的特殊模块中。(前后有两个下划线。)如果您觉得有帮助,可以将 Python 视为在启动时自动执行 from __builtin__ import *,这会将所有“内置”函数导入到命名空间中,以便您可以直接使用它们。

这种想法的好处是,您可以通过获取有关 __builtin__ 模块的信息来访问所有内置函数和属性。猜猜看,Python 有一个名为 info 的函数。现在就自己试试,浏览一下列表。稍后我们将深入探讨一些更重要的函数。(一些内置错误类,如 AttributeError,应该已经很熟悉了。)

示例 4.9. 内置属性和函数

>>> from apihelper import info
>>> import __builtin__
>>> info(__builtin__, 20)
ArithmeticError      Base class for arithmetic errors.
AssertionError       Assertion failed.
AttributeError       Attribute not found.
EOFError             Read beyond end of file.
EnvironmentError     Base class for I/O related errors.
Exception            Common base class for all exceptions.
FloatingPointError   Floating point operation failed.
IOError              I/O operation failed.

[...snip...]
Note
Python 附带了优秀的参考手册,您应该仔细阅读以了解 Python 提供的所有模块。但与大多数语言不同的是,在这些语言中,您会发现自己需要参考手册或手册页来提醒自己如何使用这些模块,而 Python 在很大程度上是自文档化的。

关于内置函数的进一步阅读