Python 2.7 系统模块学习(1) Built-in 函数

Built-in 函数
===================================================
abs(x) 求绝对值。参数可以是长整型、浮点数、复数
如果是复数,则返回该复数的模。
abs(-3)
3
>>> abs(-3)
3
>>> abs(-2.53)
2.53
>>> abs(1+3j)
3.1622776601683795
>>> abs(3+4j)
5.0
>>> abs(3-4j)
5.0

all(iterable) 
如果序列中全部为真则返回 True

any(iterable) 
如果序列中有一个为真则返回 True

basestring()
是 str 和 unicode 的抽象基类。无法被直接实例化。
可用于判断一个对象是否为 str 或 unicode. 如:
isinstanceof(obj, basestring) 等效于 
isinstanceof(obj, (str, unicode))

bin(x)
将整数转换为二进制字符串。如果 x 不是 int, 则需要定义一个 __index__() 方法以
返回整数。
>>> bin(20)
'0b10100'

bool([x])
将 x 转化为 bool. 使用 True/False 的判别规则。
bool 同时也是一个类, 它是 int 的子类。它不能被继承。

callable(object)
判断一个对象是否可被调用。如果返回 True, 那么调用仍然可能会失败;
但如果返回 False 则调用一定不会成功。类是可被调用的,调用类会返回实例。
类实例只有具有 __call__() 方法时才能被调用。

chr(i)
根据 ASCII 码返回对应的字符串(其中包含一个字符)。它是 ord() 的逆运算。
参数必须在 [0..255] 范围内。如果 i 不在范围内则会引发 ValueError. 参考 unichr().
>>> chr(97)
'a'
>>> ord('a')
97

classmethod(function)
可用 decorator 的语法,将一个函数转换为 class method.

一般形式:
class C:
@classmethod
def f(cls, arg1, arg2):
pass

例子:
>>> class Person:
@classmethod
def Hello(cls, message):
print "I'm a %s, %s!" % (cls.__name__, message)

>>> Person.Hello("hi there")
I'm a Person, hi there!
>>> Person().Hello("hi there")
I'm a Person, hi there!

在子类中被调用时,则子类被自动传入第一个参数 (cls):
>>> class Student(Person):
pass

>>> Student.Hello("hi everyone")
I'm a Student, hi everyone!

cmp(x,y)
比较两个对象的大小。
x < y 则返回负数,x == y 返回 0, x > y 则返回正数。
>>> cmp(1,2)
-1
>>> cmp(2,1)
1
>>> cmp(1,1)
0

compile(source, filename, mode[, flags[, dont_inherit]])

将 source 编译为 code 或 AST 对象。
Code 对象可被 exec 语句执行,或者用 eval() 来估算。
source 可以是 string 或 AST 对象。
参考 ast module.

例子:
>>> result = compile("""
a = 1
b = 2
c = a + b
print c""", "<string>", "exec")
>>> result
<code object <module> at 012315C0, file "<string>", line 2>
>>> exec result
3
>>> eval(result)
3

complex([real[, imag]])
构造复数,或者把字符串转换为复数。

>>> complex(3,4)
(3+4j)
>>> complex(1.1, 2.2)
(1.1+2.2j)
>>> complex("3+4j")
(3+4j)

注意在实部和虚部直接的加号两边不要加空格。否则没法正常解析:
>>> complex("3 + 4j")

Traceback (most recent call last):
  File "<pyshell#78>", line 1, in <module>
    complex("3 + 4j")
ValueError: complex() arg is a malformed string

delattr(object, name)
删除对象的属性。等效于 del object.name

>>> class Person(object):
def __init__(self, name, age):
self.Name = name
self.Age = age

>>> p = Person("Jack", 20)
>>> delattr(p, "Name")
>>> p
<__main__.Person object at 0x0122F830>
>>> p.Name

Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    p.Name
AttributeError: 'Person' object has no attribute 'Name'
>>> p.Age
20
>>> del p.Age
>>> p
<__main__.Person object at 0x0122F830>
>>> p.Age

Traceback (most recent call last):
  File "<pyshell#95>", line 1, in <module>
    p.Age
AttributeError: 'Person' object has no attribute 'Age'

dict([arg])
创建 dict 对象.

dir([object])
没有参数的情况下,返回当前 local scope 中的名称的列表。
有参数的情况下,返回参数对象的属性的列表。
对象可以实现 __dir__() 方法来返回自定义的属性列表。如果有实现,则 dir(object)
会调用到该方法。
同时也让 object 能够实现自定义的 __getattr__() 或 __getattribute__()
如果对象没有提供 __dir__() 实现,则 dir() 函数会尽可能地尝试收集对象的属性信息,
首先尝试 __dict__ 属性,然后还可能尝试搜索对象的 type object.
默认的 dir() 机制对不同类型的对象操作有所不同:

1. 如果 object 是 module 对象,则 list 由该 module 的属性名称组成。
2. 如果 object 是 type 或 class object, 则包含他们的属性名称,并且会递归的包含
其基类的属性名称。
3. 其他情况,list 中包含该对象的属性名称,以及其所属 class 的属性名称,和基类中
属性名称。

dir() 的结果按字母顺序排列。

例子:
>>> class Foo(object):
def __dir__(self):
return ["kan", "ga", "roo"]

>>> f = Foo()
>>> dir(f)
['ga', 'kan', 'roo']

divmod(a, b)
返回两个数相除的商(quotient)和余数(remainder)。
>>> divmod(100,3)
(33, 1)

enumerate(sequence[, start=0])
返回列表的可枚举的 wrapper。
利用此方法得到的 iterator 可以反复调用 next()
每次 next() 返回一个 tuple:
(index, value).

例如:
>>> for i, season in enumerate(['Spring', 'Summer', 'Fall', 'Winter']):
print i, season

0 Spring
1 Summer
2 Fall
3 Winter

eval(expression[, globals[, locals]])
例子:
>>> x = 1
>>> print eval("x+1")
2

传入的 expression 可以是字符串,也可以是 compile() 方法得到的 code 对象。
globals 和 locals 可以通过 globals() 和 locals() 分别获得当前的环境变量字典。
如果省略这两个参数,则 eval 会在调用者所在的环境中执行。

execfile(filename[, globals[, locals]])

file(filename[, mode[, bufsize]])

是 file 类型的构造器。其参数和 open() 函数的一样。
当要打开文件时,最好用 open() 而不是 file() 函数。
file 更适合用来做类型判断,如 isinstance(f, file).

filter(function, iterable)

从 iterable 中返回 function 执行结果为 True 的那些元素组成的结果。
如果 iterable 是 string 或 tuple, 则结果类型也是 string 或 tuple,
否则结果类型总是为 list.
如果 function 为 None, 则返回不为 False 的那些元素组成的结果。
filter(function, iterable) 等效于:
function 不为 None 时:
[item for item in iterable if function(item)]
function 为 None 时:
[item for item in iterable if item]

posted on 2010-07-17 23:38  NeilChen  阅读(1288)  评论(0编辑  收藏  举报

导航