您当前位置:首页 > 深入 Python > 自省的威力 > 使用 type、str、dir 和其他内置函数 | << >> | ||||
深入 Python从 Python 新手到专家 |
Python 有一小组非常有用的内置函数。所有其他函数都被划分到模块中。这实际上是一个有意识的设计决定,是为了防止核心语言像其他脚本语言(咳咳,Visual Basic)那样臃肿。
type 函数返回任意对象的數據类型。可能的类型列在 types 模块中。这对于可以处理多种数据类型的辅助函数很有用。
str 将数据强制转换为字符串。每种数据类型都可以强制转换为字符串。
>>> str(1)'1' >>> horsemen = ['war', 'pestilence', 'famine'] >>> horsemen ['war', 'pestilence', 'famine'] >>> horsemen.append('Powerbuilder') >>> str(horsemen)
"['war', 'pestilence', 'famine', 'Powerbuilder']" >>> str(odbchelper)
"<module 'odbchelper' from 'c:\\docbook\\dip\\py\\odbchelper.py'>" >>> str(None)
'None'
info 函数的核心是强大的 dir 函数。dir 返回任何对象的属性和方法的列表:模块、函数、字符串、列表、字典……几乎任何东西。
>>> li = [] >>> dir(li)['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> d = {} >>> dir(d)
['clear', 'copy', 'get', 'has_key', 'items', 'keys', 'setdefault', 'update', 'values'] >>> import odbchelper >>> dir(odbchelper)
['__builtins__', '__doc__', '__file__', '__name__', 'buildConnectionString']
最后,callable 函数接受任何对象,如果该对象可以被调用,则返回 True,否则返回 False。可调用对象包括函数、类方法,甚至类本身。(下一章将详细介绍类。)
>>> import string >>> string.punctuation'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' >>> string.join
<function join at 00C55A7C> >>> callable(string.punctuation)
False >>> callable(string.join)
True >>> print string.join.__doc__
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)
![]() |
string 模块中的函数已弃用(尽管许多人仍在使用 join 函数),但该模块包含许多有用的常量,例如 string.punctuation,其中包含所有标准标点符号。 |
![]() |
string.join 是一个连接字符串列表的函数。 |
![]() |
string.punctuation 不可调用;它是一个字符串。(字符串确实有可调用的方法,但字符串本身不可调用。) |
![]() |
string.join 可调用;它是一个接受两个参数的函数。 |
![]() |
任何可调用对象都可以有一个 docstring。通过对对象的每个属性使用 callable 函数,您可以确定哪些属性是您关心的(方法、函数、类),哪些属性是您想忽略的(常量等),而无需事先了解该对象。 |
type、str、dir 以及所有其他 Python 内置函数都被分组到一个名为 __builtin__ 的特殊模块中。(前后有两个下划线。)如果您觉得有帮助,可以将 Python 视为在启动时自动执行 from __builtin__ import *,这会将所有“内置”函数导入到命名空间中,以便您可以直接使用它们。
这种想法的好处是,您可以通过获取有关 __builtin__ 模块的信息来访问所有内置函数和属性。猜猜看,Python 有一个名为 info 的函数。现在就自己试试,浏览一下列表。稍后我们将深入探讨一些更重要的函数。(一些内置错误类,如 AttributeError,应该已经很熟悉了。)
>>> 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...]
![]() |
|
Python 附带了优秀的参考手册,您应该仔细阅读以了解 Python 提供的所有模块。但与大多数语言不同的是,在这些语言中,您会发现自己需要参考手册或手册页来提醒自己如何使用这些模块,而 Python 在很大程度上是自文档化的。 |
<< 使用可选参数和命名参数 |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |
使用 getattr 获取对象引用 >> |