Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2109868
  • 博文数量: 333
  • 博客积分: 10161
  • 博客等级: 上将
  • 技术积分: 5238
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-19 08:59
文章分类

全部博文(333)

文章存档

2017年(10)

2014年(2)

2013年(57)

2012年(64)

2011年(76)

2010年(84)

2009年(3)

2008年(37)

分类: Python/Ruby

2010-12-16 13:59:05

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

内置函数


id()

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

>>>>>> def Foo():  
pass

>>>>>> Foo
<function Foo at 0x00DC6EB0>
>>>>>> hex(id(Foo))
'0xdc6eb0'
>>>>>>

 

dir()

方法 dir() 能帮我们了解对象包含哪些成员。

>>>>>> dir(Foo)  
[
'__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
>>>>>>

 

type()

type() 让我们知道变量的实际类型。

>>>>>> type(Foo)  
<type 'function'>
>>>>>>

 

isinstance()

isinstance() 可以确认某个变量是否某种类型。

>>>>>> s = "Xwy2.com"  
>>>>>> isinstance(s, str)
True
>>>>>>

 

issubclass()

该函数可以判断继承关系。

>>>>>> issubclass(int,object)  
True
>>>>>>

 

is

多数情况下,我们可以直接使用 "==" 来判断两个对象是否相等。但 Python 同样支持运算符重载,因此使用 is 来代替应该更安全一点(C# 中经典的 Equals 问题)。

>>>>>> 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 自省指

转载自:

阅读(1668) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~