您的位置:首页 > 编程语言 > Python开发

Python 学习笔记 - 2.自省

2008-09-04 13:01 826 查看
转载自:http://www.xwy2.com/article.asp?id=106

在学习 Python 之前,我们先学几个内置函数,这对于了解 Python 的一些原理是非常有用的。

内置函数

id()

如果我们能获取对象(变量、方法或类型实例)的 "内存地址" 对于我们了解引用机制还是非常不错的。
id() 返回一个对象的 "唯一序号",转换成 16 进制就是所谓的内存地址了,为了图方便后面直接使用 id(),不再转换成 16 进制。

>>>>>> class MyClass:
def __ini__(Self):
self.x = 123
def __eq__(self, o):
return self.x == o.x

>>>>>> a = MyClass()
>>>>>> b = MyClass()
>>>>>> print hex(id(a))
0xdcea80
>>>>>> print hex(id(b))
0xdc4b98
>>>>>> print a == b
true
>>>>>> print a is b
false


LoongTsui按:Python里一切均是对象,Python 提供了很棒的自省能力,自省揭示了关于程序对象的有用信息。Python自带的Help指令就是有其自省能力实现的,下面补充一下对Help指令的介绍

Python帮助help指令

启动Help指令

引用
>>> help()

Welcome to Python 2.5! This is the online help utility.

..省略号

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

help>

输入help()会启动help指令,最后进入help>提示符,如果输入keywords,将列出Python的所有关键字:

引用
help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

and elif if print
as else import raise
assert except in return
break exec is try
class finally lambda while
continue for not with
def from or yield
del global pass

输入modules将列出Python所有可用的模块:

引用
...省略号
PathBrowser binascii mailbox sys
Percolator binhex mailcap tabnanny
PyParse bisect markupbase tabpage
...省略号

可以输入上面列出的所有指令,查看其帮助信息

help指令还有使用方式,在 Python Shell 提示符>>>下,输入 help("modules") 这样。

上面介绍的内置函数和help实用程序是很方便很有用处的。

关于自省的更为详细的介绍,请参见:Python 自省指南
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: