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

python built-in function 学习笔记

2011-09-27 20:57 1121 查看
part 1: 几个参考的页面:

built-in functions:
http://docs.python.org/library/functions.html
python 内建函数:
http://hi.baidu.com/c2cjushi/blog/item/3cb669eed23abb372797916c.html
part 2: 自己的阅读心得

python 内置的函数列表: 5*16 = 80

Built-in Functions

abs() divmod() input() open() staticmethod()

all() enumerate() int() ord() str()

any() eval() isinstance() pow() sum()

basestring() execfile() issubclass() print() super()

bin() file() iter() property() tuple()

bool() filter() len() range() type()

bytearray() float() list() raw_input() unichr()

callable() format() locals() reduce() unicode()

chr() frozenset() long() reload() vars()

classmethod() getattr() map() repr() xrange()

cmp() globals() max() reversed() zip()

compile() hasattr() memoryview() round() __import__()

complex() hash() min() set() apply()

delattr() help() next() setattr() buffer()

dict() hex() object() slice() coerce()

dir() id() oct() sorted() intern()

# 这里共有5列,一列为一组;
# 我的原则是: 先自己看,试着写,遇到问题再去看别人的网页

1.1 : abs() 去一个数的绝对值:
abs(...)

abs(number) -> number

Return the absolute value of the argument.

eg:
>>> abs(-1)

1

>>>

1.2 all() 判断iterator 的元素是否都是非空,"一假为假"

all(...)

all(iterable) -> bool

Return True if bool(x) is True for all values x in the iterable.

1.3 any() 判断iterator 的元素是否有非空值, "一真为真"

一个关于 all() 和 any() 的例子:

>>> tst = ['a', 'b','c']

>>> all(tst)

True

>>> any(tst)

True

>>> tst2 = ['a', 'b', '']

>>> all(tst2)

False

>>> any(tst2)

True

1.4 basestring() 严格来说,basestring 是一个 类。 python 中基本的字符串类型

class basestring(object)

| Type basestring cannot be instantiated; it is the base for str and unicode.

|

| Data and other attributes defined here:

|

| __new__ = <built-in method __new__ of type object>

| T.__new__(S, ...) -> a new object with type S, a subtype of T

This abstract type is the superclass for str and unicode. It cannot be called or instantiated, but it can be used to test whether an object is an instance of str or

unicode.isinstance(obj, basestring) is equivalent to isinstance(obj, (str, unicode)).

一个例子:

>>> isinstance('aa',basestring)

True

>>> isinstance(11,basestring)

False

>>> isinstance(u'jia',basestring)

True

1.5 bin() 返回一个整型或长整型的二进制表示(以0b开头)

bin(...)

bin(number) -> string

Return the binary representation of an integer or long integer.

一个例子:

>>> bin(1)

'0b1'

>>> bin(0)

'0b0'

>>> bin(8)

'0b1000'

1.6 bool() 一个类

class bool(int)

| bool(x) -> bool

|

| Returns True when the argument x is true, False otherwise.

| The builtins True and False are the only two instances of the class bool.

| The class bool is a subclass of the class int, and cannot be subclassed.

|

| Method resolution order:

| bool

| int

| object


一个例子:

>>> bool('2')

True

>>> bool('')

False

>>> bool(1+2>5)

False

>>> bool(1+2<5)

True

1.7 bytearray() 返回一个字节数组
# 详细用法可以研究!!! # todo

class bytearray(object)

| bytearray(iterable_of_ints) -> bytearray.

| bytearray(string, encoding[, errors]) -> bytearray.

| bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray.

| bytearray(memory_view) -> bytearray.

|

| Construct an mutable bytearray object from:

| - an iterable yielding integers in range(256)

| - a text string encoded using the specified encoding

| - a bytes or a bytearray object

| - any object implementing the buffer API.

|

| bytearray(int) -> bytearray.

|

| Construct a zero-initialized bytearray of the given length.

|

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String
Methods.

The optional source parameter can be used to initialize the array in a few different ways:

* If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

* If it is an integer, the array will have that size and will be initialized with null bytes.

* If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

* If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created

一个例子:

>>> bytearray(8)

bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00')

>>> for k in bytearray(8):

... print k

...

...

0

0

0

0

0

0

0

0

>>> type(k)

<type 'int'>

>>> for k in bytearray('jia'):

... print k

...

...

106

105

97

1.8 callable() 判断对象时候可以调用; 返回值为true 的对象不一定能call, 返回值为 false 一定不可以调用

callable(...)

callable(object) -> bool

Return whether the object is callable (i.e., some kind of function).

Note that classes are callable, as are instances with a __call__() method.

Return True if the object argument appears callable, False if not. If this returns true, it is still possible that a call fails, but if it is false, calling object will never succeed. Note that classes are callable (calling a class returns a new instance);
class instances are callable if they have a __call__() method.

>>> class Test():

... def test(self):

... print ' test method'

>>> callable(Test)

True

>>> callable(Test())

False

>>> tst = Test()

>>> tst.test()

test method

>>> callable(tst)

False

>>> class Test2():

... def __call__(self):

... print 'this is call method'

>>> callable(Test2)

True

>>> callable(Test2())

True

>>>

1.9 chr() 显示数字对应的ASCII吗

chr(...)

chr(i) -> character

Return a string of one character with ordinal i; 0 <= i < 256.

Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

一个例子:
>>> chr(97)

'a'

相比:

>>> ord('a')

97

>>> bin(97)

'0b1100001'

1.10 classmethod() 类似 staticmethod

class classmethod(object)

| classmethod(function) -> method

|

| Convert a function to be a class method.

|

| A class method receives the class as implicit first argument,

| just like an instance method receives the instance.

| To declare a class method, use this idiom:

|

| class C:

| def f(cls, arg1, arg2, ...): ...

| f = classmethod(f)

|

| It can be called either on the class (e.g. C.f()) or on an instance

| (e.g. C().f()). The instance is ignored except for its class.

| If a class method is called for a derived class, the derived class

| object is passed as the implied first argument.

|

| Class methods are different than C++ or Java static methods.

| If you want those, see the staticmethod builtin.

例子请参见 staicmethod()

1.11 cmp() 比较两个值的大小

cmp(...)
cmp(x, y) -> integer

Return negative if x<y, zero if x==y, positive if x>y.

Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x < y, zero if x == y and strictly positive if x > y.

一个例子:
>>> cmp(1,4)

-1

>>> cmp(5,4)

1

>>> cmp(4,4)

0

>>>

# 其实,项目中的 经纬度点的过滤算法可以用到这个方法

1.12 compile()

compile(...)

compile(source, filename, mode[, flags[, dont_inherit]]) -> code object

Compile the source string (a Python module, statement or expression)

into a code object that can be executed by the exec statement or eval().

The filename will be used for run-time error messages.

The mode must be 'exec' to compile a module, 'single' to compile a

single (interactive) statement, or 'eval' to compile an expression.

The flags argument, if present, controls which future statements influence

the compilation of the code.

The dont_inherit argument, if non-zero, stops the compilation inheriting

the effects of any future statements in effect in the code calling

compile; if absent or zero these statements do influence the compilation,

in addition to any features explicitly specified.

#NOTE: 这个没调通

1.13 complex() 得到一个复数

class complex(object)

| complex(real[, imag]) -> complex number

|

| Create a complex number from a real part and an optional imaginary part.

| This is equivalent to (real + imag*1j) where imag defaults to 0.

>>> complex(1,2)

(1+2j)

>>> complex(1)

(1+0j)

1.14 delattr() 删除一个对象的一个属性

delattr(...)

delattr(object, name)

Delete a named attribute on an object; delattr(x, 'y') is equivalent to

``del x.y''.

一个例子:

class Test():
name = 'test'
age = 20

def show(self):
print 'name
is ', self.name , '
sex is ', self.age

a = Test()
a.name = 'jia'
a.show()
#delattr(Test,
'name')
delattr(a,
'name')
#Test().show()
print a.name
a.show()
# 所谓的delattr(object,name). 对于实例来说, 必须是主动给实例的属性赋值,否则,即使继承了父类的属性值,也不可以用 delattr()。
就像程序中,若要使用 delattr(a,
'name'),必须 a.name = 'jia'

1.15 dict() 根据传入的 key=value pairs 生成一个新的 dict
class dict(object)

| dict() -> new empty dictionary

| dict(mapping) -> new dictionary initialized from a mapping object's

| (key, value) pairs

| dict(iterable) -> new dictionary initialized as if via:

| d = {}

| for k, v in iterable:

| d[k] = v

| dict(**kwargs) -> new dictionary initialized with the name=value pairs

| in the keyword argument list. For example: dict(one=1, two=2)

>>> dict(a = 'tsinghua', b = 'beijin')

{'a': 'tsinghua', 'b': 'beijin'}

1.16 dir() 其实就是看到所选对象可用的属性
dir(...)

dir([object]) -> list of strings

If called without an argument, return the names in the current scope.

Else, return an alphabetized list of names comprising (some of) the attributes

of the given object, and of attributes reachable from it.

If the object supplies a method named __dir__, it will be used; otherwise

the default dir() logic is used and returns:

for a module object: the module's attributes.

for a class object: its attributes, and recursively the attributes

of its bases.

for any other object: its attributes, its class's attributes, and

recursively the attributes of its class's base classes.

>>> a = 'jia'

>>> b = dir(a)

>>> b

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

>>> c = dir()

>>> c

['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']

2.1 : divmod() 对一个表达式进行求余数和商数的计算:

divmod(...)

divmod(x, y) -> (div, mod)

Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.

eg:

>>> divmod(10,3)

(3, 1)

>>> a, b = divmod(10, 3)

>>> a

3

>>> b

1

>>>

2.2 enumerate() # 对传入的迭代对象进行迭代,返回迭代对象中的元素和相应的索引。

class enumerate(object)

| enumerate(iterable[, start]) -> iterator for index, value of iterable

|

| Return an enumerate object. iterable must be another object that supports

| iteration. The enumerate object yields pairs containing a count (from

| start, which defaults to zero) and a value yielded by the iterable argument.

| enumerate is useful for obtaining an indexed list:

| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

|

| Methods defined here:

|

| __getattribute__(...)

| x.__getattribute__('name') <==> x.name

|

| __iter__(...)

| x.__iter__() <==> iter(x)

|

| next(...)

| x.next() -> the next value, or raise StopIteration

|

| ----------------------------------------------------------------------

| Data and other attributes defined here:

|

| __new__ = <built-in method __new__ of type object>

| T.__new__(S, ...) -> a new object with type S, a subtype of T

>>> a = 'jia'
>>> for k,v in enumerate(a):
... print k, v

...

0 j

1 i

2 a

>>> for k,v in enumerate(a,2):

... print k, v

...

2 j

3 i

4 a

>>>

2.3 eval() # 执行一个指定的字符串; 求值,有返回结果

eval(...)

eval(source[, globals[, locals]]) -> value

Evaluate the source in the context of globals and locals.

The source may be a string representing a Python expression

or a code object as returned by compile().

The globals must be a dictionary and locals can be any mapping,

defaulting to the current globals and locals.

If only globals is given, locals defaults to it.

>>> eval('5-4')
1

>>> cal = "7-8+11"

>>> eval(cal)

10

2.4 execfile() # 类似exec, 只是参数来源于一个file

execfile(...)

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

Read and execute a Python script from a file.

The globals and locals are dictionaries, defaulting to the current

globals and locals. If only globals is given, locals defaults to it.

# 呵呵,这有点像 shell 的输入重定向

>>> exec("print '11'")

11

# 将上面的“print 11" 写在 ex.py 文件中

>>> execfile("ex.py")

11

2.5 file() # 关于文件操作的一些

class file(object)

| file(name[, mode[, buffering]]) -> file object

|

| Open a file. The mode can be 'r', 'w' or 'a' for reading (default),

| writing or appending. The file will be created if it doesn't exist

| when opened for writing or appending; it will be truncated when

| opened for writing. Add a 'b' to the mode for binary files.

| Add a '+' to the mode to allow simultaneous reading and writing.

| If the buffering argument is given, 0 means unbuffered, 1 means line

| buffered, and larger numbers specify the buffer size. The preferred way

| to open a file is with the builtin open() function.

| Add a 'U' to mode to open the file for input with universal newline

| support. Any line ending in the input file will be seen as a '\n'

| in Python. Also, a file so opened gains the attribute 'newlines';

| the value for this attribute is one of None (no newline read yet),

| '\r', '\n', '\r\n' or a tuple containing all the newline types seen.

|

| 'U' cannot be combined with 'w' or '+' mode.

# 这里的file() 返回一个文件对象,
# TODO: 关于文件的操作其实有很多内容,有时间可以添加进来

2.6 filter() 对传入的列表做过滤,过滤条件为function.

filter(...)

filter(function or None, sequence) -> list, tuple, or string

Return those items of sequence for which function(item) is true. If

function is None, return the items that are true. If sequence is a tuple

or string, return the same type, else return a list.

>>> def test(value):

... return value>10

...

>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13]

>>> filter(test,a)

[11, 12, 13]

2.7 float() 构建一个浮点型的对象

class float(object)

| float(x) -> floating point number

|

| Convert a string or number to a floating point number, if possible.

|

| Methods defined here:

|

| __abs__(...)

| x.__abs__() <==> abs(x)

|

| __add__(...)

| x.__add__(y) <==> x+y

>>> float(1)

1.0

>>> float(10)

10.0

2.8 format()

format(...)

format(value[, format_spec]) -> string

Returns value.__format__(format_spec)

format_spec defaults to ""

>>> format('jia','')

'jia'

>>> format('jia')

'jia'

# 坦率的说,这个不是太熟悉,感觉没什么用

2.9 frozenset()

class frozenset(object)

| frozenset() -> empty frozenset object

| frozenset(iterable) -> frozenset object

|

| Build an immutable unordered collection of unique elements.

|

| Methods defined here:

|

| __and__(...)

| x.__and__(y) <==> x&y

|

| __cmp__(...)

| x.__cmp__(y) <==> cmp(x,y)

# 简单来说就是构建一个无序的set

>>> a = [1,2,3,3,3,]

>>> frozenset(a)

frozenset([1, 2, 3])

>>> b = frozenset(a)

>>> b

frozenset([1, 2, 3])

>>> for k in b:

... print k

...

1

2

3

2.10 getattr() 获取一个对象的属性

getattr(...)

getattr(object, name[, default]) -> value

Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.

When a default argument is given, it is returned when the attribute doesn't

exist; without it, an exception is raised in that case.

>>> class person():

... name = 'jia'

...

>>> p = person()

>>> p.name

'jia'

>>> getattr(p,'name')

'jia'

2.11 globals() 返回一个当前作用域的key,value pairs
# 其实,可以比较locals(), vars(), locals() 一起学习

globals(...)

globals() -> dictionary

Return the dictionary containing the current scope's global variables.

>>> globals()

{'a': [1, 2, 3, 3, 3], 'b': frozenset([1, 2, 3]), '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, '__package__': None, 'test': <function test at 0x7f0fe09f0500>, '__name__': '__main__', '__doc__': None}

>>> vars()

{'a': [1, 2, 3, 3, 3], 'b': frozenset([1, 2, 3]), '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, '__package__': None, 'test': <function test at 0x7f0fe09f0500>, '__name__': '__main__', '__doc__': None}

>>> locals()

{'a': [1, 2, 3, 3, 3], 'b': frozenset([1, 2, 3]), '__builtins__': <module '__builtin__' (built-in)>, 'k': 3, '__package__': None, 'test': <function test at 0x7f0fe09f0500>, '__name__': '__main__', '__doc__': None}

2.12 hasattr() 判断一个对象中是否有某个属性

hasattr(...)

hasattr(object, name) -> bool

Return whether the object has an attribute with the given name.

(This is done by calling getattr(object, name) and catching exceptions.)

>>> hasattr(p,'name')

True

# getattr, hasattr 的区别。对于一个不存在的属性。getattr 是会报异常的。hasattr() 不会。 我疑心底层实现中,改成: 如果property不存在,getattr 直接返回None 会更好一些。(只是个人猜测!)

>>> getattr(p,'names')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

AttributeError: person instance has no attribute 'names'

>>> hasattr(p,'names')

False



2.13 hash() 得到一个对象的哈希值。 ”值相同的对象拥有相同的hash 值,hash 值相同,对象也大多数相同“

hash(...)

hash(object) -> integer

Return a hash value for the object. Two objects with the same value have

the same hash value. The reverse is not necessarily true, but likely.

>>> hash(b)

-7699079583225461316

>>> hash(a)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unhashable type: 'list'

2.14 help() 应该说是在命令行最常用的方法了,比如>>help(help), >>help(hash)

class _Helper(__builtin__.object)

| Define the built-in 'help'.

| This is a wrapper around pydoc.help (with a twist).

|

| Methods defined here:

|

| __call__(self, *args, **kwds)

|

| __repr__(self)

|

| ----------------------------------------------------------------------

| Data descriptors defined here:

|

| __dict__

| dictionary for instance variables (if defined)

|

| __weakref__

| list of weak references to the object (if defined)

读取内部的 __doc__,
自己定义的一些函数也会被调用!!

>>> def test():

... """ this is a doc test"""

...
>>> test.__doc__

' this is a doc test'

>>> help(test)

2.15 hex() 将一个十进制的数转换为16进制

hex(...)

hex(number) -> string

Return the hexadecimal representation of an integer or long integer.

>>> hex(20)

'0x14'

>>> hex(20L)

'0x14L'

>>> hex(20l)

'0x14L'

>>> a = hex(20l)

>>> int(a)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: invalid literal for int() with base 10: '0x14L'

>>> long(a)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: invalid literal for long() with base 10: '0x14L'

# 其实我一直想知道,把一个long 型转为16进制有何用!

2.16 id() 返回一个对象的唯一id

id(...)

id(object) -> integer

Return the identity of an object. This is guaranteed to be unique among

simultaneously existing objects. (Hint: it's the object's memory address.)

>>> id(p)

140165793784968

>>> id([1,2,])

25908792

>>> id([1,2,3])

25908792

>>> id([1,2,3,4])

25908792

>>> a = [1,2]

>>> id(a)

25908792

>>> b=[1,2,3]

>>> id(b)

25912240

>>> a.append(5)

>>> a

[1, 2, 5]

>>> id(a)

25908792

>>> id([1,23,5])

140165793639096

>>> id([1,2,5])

140165793639096

>>> id([1,2,5,6])

140165793639096

>>> id([1,2,5,6,7])
>>> id([7])

140165793639096

>>> id([])

140165793639096

140165793639096
# 基本上还是可信的,有人可以解释一下id(list) 的返回值为何相同吗?

3.1 input() 接收屏幕的一个输入值

input(...)

input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).

eg:

>>> input('please input your age: ')

please input you age: 29

29

>>> raw_input('please input your age: ')

please input your age: 12

'12'

3.2 int() 得到一个interger 对象

class int(object)

| int(x[, base]) -> integer

|

| Convert a string or number to an integer, if possible. A floating point

| argument will be truncated towards zero (this does not include a string

| representation of a floating point number!) When converting a string, use

| the optional base. It is an error to supply a base when converting a

| non-string. If base is zero, the proper base is guessed based on the

| string content. If the argument is outside the integer range a

| long object will be returned instead.

|

| Methods defined here:

|

| __abs__(...)

| x.__abs__() <==> abs(x)

|

| __add__(...)

#todo
>>> int(-1)

-1

>>> int("12")

12

>>> int("12",16)

18

>>> int("12",8)

10

>>>

3.3 isinstance() 判断一个对象是否属于某一个类

isinstance(...)

isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof.

With a type as second argument, return whether that is the object's type.

The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for

isinstance(x, A) or isinstance(x, B) or ... (etc.).

一个简单的方法:
AKV, 对一个i对象进行多种实例判断的快捷方式: isinstance(x,(A,B,C))

一个举例:
>>> a = [1,2,3]

>>> b = (1,2,3)

>>> if isinstance(a,list):

... print 'list'

... elif isinstance(b,tuple):

... print 'b tuple'

... elif isinstance(a,tuple):

... print 'a tuple'

... elif isinstance(b,list):

... print 'b tuple'

...

list

>>> type(a)

<type 'list'>

>>> type(b)

<type 'tuple'>

>>>

3.4 issubclass() 判断一个类是否是另一个类的子类

issubclass(...)

issubclass(C, B) -> bool

Return whether class C is a subclass (i.e., a derived class) of class B.

When using a tuple as the second argument issubclass(X, (A, B, ...)),

is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).

# 这里和isinstance(x,(A,B,C)) 一样,也可以一次判断多个

>>> class A():

... def test(self):

... print 'this is A'

...

>>> class B(A):

... def test(self):

... print 'this is B'

...
>>> issubclass(B,A)

True

3.5 iter()

iter(...)

iter(collection) -> iterator

iter(callable, sentinel) -> iterator

Get an iterator from an object. In the first form, the argument must

supply its own iterator, or be a sequence.

In the second form, the callable is called until it returns the sentinel.

# 第一种方法: collection 必须支持__iter_(), __getitem__() 方法,否则抛出TypeError 异常
>>> a = iter([1,2,3])

>>> a

<listiterator object at 0x7fc78b770850>

>>> for k in a:

... print k

...

1

2

3

这么看来, 有了enumerate, 完全可以不用iter() 了。
# 第二种方法看不太明白!
第二种方法特别适合打开一个文件,一行一行处理文本,直到遇到特定的行。
# 将几行文字写入 bbbb.txt 文件。
>>> with open("bbbb.txt") as fp:

... for line in iter(fp.readline, 'stop'):

... print line

...

1 1

2 2

3 3

4 4

5 5

6 6

7 7

8 8

9 9

stop

# 参考别人的例子写了一个, 和期望的不一样, 读到 'stop' 行之后, 还继续往下读!!?? # TODO

3.6 len() 返回一个序列的元素的个数

len(...)

len(object) -> integer

Return the number of items of a sequence or mapping.

>>> len('jia')

3

>>> len([1,2,3])

3

3.7 list()
class list(object)

| list() -> new empty list

| list(iterable) -> new list initialized from iterable's items

|

| Methods defined here:

|

| __add__(...)

| x.__add__(y) <==> x+y

|

| __contains__(...)

| x.__contains__(y) <==> y in x

# 通过一个可迭代的对象,得到其中元素说组成的列表。

>>> list('jia')

['j', 'i', 'a']

>>> list([1,2,3])

[1, 2, 3]

>>> list((1,2,3))

[1, 2, 3]

>>> list({'a':1,'b':2,'c':3})

['a', 'c', 'b']

# 让我有点惊讶的是 对dict 的迭代,这里竟然也可以成功。,返回一个key 的列表。很显然,如果要得到一个dict 的列表,可以不使用这个!!

3.8 locals()

locals(...)

locals() -> dictionary

Update and return a dictionary containing the current scope's local variables.

# 具体参考之前的globals(), 返回一个当前作用域的key-value pairs

3.9 long()

class long(object)

| long(x[, base]) -> integer

|

| Convert a string or number to a long integer, if possible. A floating

| point argument will be truncated towards zero (this does not include a

| string representation of a floating point number!) When converting a

| string, use the optional base. It is an error to supply a base when

| converting a non-string.

|

| Methods defined here:

|

| __abs__(...)

| x.__abs__() <==> abs(x)

|

| __add__(...)

| x.__add__(y) <==> x+y

返回一个长整型的数据。

3.10 map() 对一个序列中的每个元素进行function 操作。

map(...)

map(function, sequence[, sequence, ...]) -> list

Return a list of the results of applying the function to the items of

the argument sequence(s). If more than one sequence is given, the

function is called with an argument list consisting of the corresponding

item of each sequence, substituting None for missing values when not all

sequences have the same length. If the function is None, return a list of

the items of the sequence (or a list of tuples if more than one sequence).

# 可以参看 filter(function, sequence). filter 是对sequence中的每个元素调用function,如果返回为false, 该元素就不会返回。
# map 是对每个元素都执行function, function 的返回结果作为新的参数被输出。
>>> def add_5(value):

... return value+5

...

>>> map(add_5,[1,2,3,4])

[6, 7, 8, 9]

3.11 max()

max(...)

max(iterable[, key=func]) -> value

max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.

With two or more arguments, return the largest argument.

# 这里的缺省参数key 可以调研。

>>> max([1,2,3,4,5,6,7,45,2,43,])

45

>>> max(['jia','luo','guo'])

'luo'

# 一直想传递一个参数 key = function, 不知道改如何传!!?
def test(a,b):
aa = a[0]
bb = b[0]
if ord(aa)
> ord(bb):
return True
print max([1,2,3])
lst = ['jia','luo','guo']
print max(*lst, key=test)
# 现在明白了。 定义的函数func, 不是用来实现比较的逻辑的。是为了对其中的每一个元素做比较的
def test(a):
return a*2
def test2(a):
return a%3
print
max([1,2,3,4],key=test2)
lst = ['jia','luo','guo']
print
max(*lst, key=test)

3.12 memoryview()

# 在命令行中竟然找不到这个方法,在其他人的博客中也没有这个方法,再确认!!!#TODO

3.13 min()

min(...)

min(iterable[, key=func]) -> value

min(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its smallest item.

With two or more arguments, return the smallest argument.

# 具体参考 max()

3.14 next()

next(...)

next(iterator[, default])

Return the next item from the iterator. If default is given and the iterator

is exhausted, it is returned instead of raising StopIteration.

>>> a = [1,2,3,4]

>>> b = iter(a)

>>> next(b)

1

>>> next(b)

2

>>> next(b)

3

>>> next(b)

4

>>> next(b)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

StopIteration

# 对于那些固定值得参数时可以的。

3.15 object()

class object

| The most base type

# 最基本的类。 在定义类的时候
# 最基本的方法由C底层实现,看不到源码!

3.16 oct()

oct(...)

oct(number) -> string

Return the octal representation of an integer or long integer.

# 类似hex(), 返回一个数的八进制表示!

>>> oct(1)

'01'

>>> oct(2)

'02'

>>> oct(122)

'0172'

>>> oct(16)

'020'

>>> hex(16)

'0x10'

4.1 open() 打开一个文件,

open(...)

open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object. This is the

preferred way to open a file.

# 建立一个文件 a.txt, 输入一段文字

>>> f = open('a.txt')

>>> f.readline()

'hello, world!\n'

>>>

4.2 ord() 仿佛单字节字符对应的ascii 码

ord(...)

ord(c) -> integer

Return the integer ordinal of a one-character string.

>>> ord('a')

97

>>> ord('\x20')

32

>>> ord('12')

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: ord() expected a character, but string of length 2 found



4.3 pow()

pow(...)

pow(x, y[, z]) -> number

With two arguments, equivalent to x**y. With three arguments,

equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

# 求幂运算

>>> 2**4

16

>>> pow(2,4)

16

>>> pow(2,4,3)

1

>>> (2**4) % 3

1

4.4 print()

这里竟然help不可以,!!??

4.5 property()

class property(object)

| property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

|

| fget is a function to be used for getting an attribute value, and likewise

| fset is a function for setting, and fdel a function for del'ing, an

| attribute. Typical use is to define a managed attribute x:

| class C(object):

| def getx(self): return self._x

| def setx(self, value): self._x = value

| def delx(self): del self._x

| x = property(getx, setx, delx, "I'm the 'x' property.")

|

| Decorators make defining new properties or modifying existing ones easy:

| class C(object):

| @property

| def x(self): return self._x

| @x.setter

| def x(self, value): self._x = value

| @x.deleter

| def x(self): del self._x

|

| Methods defined here:

|

| __delete__(...)

| descr.__delete__(obj)

|

| __get__(...)

| descr.__get__(obj[, type]) -> value

# property 的确是一个值得研究的方法。
最常见的应用就是 在一个方法前添加 @property, 使得方法的调用就像属性一样来使用。(其实在调用的时候, 方法还是会依次执行的)

4.6 range()

range(...)

range([start,] stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.

range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.

When step is given, it specifies the increment (or decrement).

For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!

These are exactly the valid indices for a list of 4 elements.

# 获取一个序列,逐渐被xrange()替代

4.7 raw_input()

raw_input(...)
raw_input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped.

If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.

On Unix, GNU readline is used if enabled. The prompt string, if given,

is printed without a trailing newline before reading.

# 确切的来说,这个只有在命令行会使用,接受一个命令行输入

>>> raw_input('please input a number: ')

please input a number: 12

'12'

>>>

# 在程序中可以接受一些命令行中的输入:

# tip2: define a list of switch
SWITCHES = ['realtime','remotelisten','remoteonoff','enterexitbound',
'removebound','upload_data','login','logout','active_test',
'whitelist','scheduleset','scheduleremove','schedulequery','scheduleonoff']
def usage():
print 'please
input one iterm of the follows:'
for switch in SWITCHES:
print switch



def main():
while True:
switch = raw_input("Input
your command: ")
if switch not in SWITCHES:
usage()
else:
# do something

if __name__
== '__main__':
main()

4.8 reduce()

reduce(...)

reduce(function, sequence[, initial]) -> value

Apply a function of two arguments cumulatively to the items of a sequence,

from left to right, so as to reduce the sequence to a single value.

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates

((((1+2)+3)+4)+5). If initial is present, it is placed before the items

of the sequence in the calculation, and serves as a default when the

sequence is empty.

# 很类似 map() , filter() , 一个区别是reduce() 一般不能被列表推导式list comprehension 代替。
将序列中的前两个参数提供给指定的函数使用,然后将返回值和第三个参数提供给指定的函数使用,依次类推。。。
个人觉得: 用处不是太大,不是太有用!!

4.9 reload()

reload(...)

reload(module) -> module

Reload the module. The module must have been successfully imported before.

# 重新加载一个module, 看起来似乎没什么用!!

>>> import struct

>>> reload(struct)

<module 'struct' from '/usr/lib/python2.6/struct.pyc'>

>>> help(struct)

4.10 repr()

repr(...)

repr(object) -> string

Return the canonical string representation of the object.

For most object types, eval(repr(object)) == object.

# 返回一个对象的标准、规范表示

4.11 reversed()

class reversed(object)

| reversed(sequence) -> reverse iterator over values of the sequence

|

| Return a reverse iterator

|

| Methods defined here:

|

| __getattribute__(...)

| x.__getattribute__('name') <==> x.name

|

| __iter__(...)

| x.__iter__() <==> iter(x)

|

| __length_hint__(...)

| Private method returning an estimate of len(list(it)).

|

| next(...)

| x.next() -> the next value, or raise StopIteration

# 其实是接受一个序列,返回一个迭代器。 有用吗?貌似用处不大

>>> a = [1,2,3,4,5]

>>> b = reversed(a)

>>> b

<listreverseiterator object at 0x7fb1deecf7d0>

>>> for k in b:

... print k

...

5

4

3

2

1

>>>

4.12 round()

round(...)

round(number[, ndigits]) -> floating point number

Round a number to a given precision in decimal digits (default 0 digits).

This always returns a floating point number. Precision may be negative.

# number 后的 ndigits 似乎没有作用!
>>> round(2.3)

2.0

>>> round(2.3,2)

2.2999999999999998

>>> round(2.3,3)

2.2999999999999998

>>> round(2.3,10)

2.2999999999999998

>>> round(2.0,10)

2.0

>>> round(2.0,1)

2.0

>>> round(2.0,3)

2.0

4.13 set()

class set(object)

| set() -> new empty set object

| set(iterable) -> new set object

|

| Build an unordered collection of unique elements.

|

| Methods defined here:

|

| __and__(...)

| x.__and__(y) <==> x&y

|

| __cmp__(...)

| x.__cmp__(y) <==> cmp(x,y)

|

| __contains__(...)

| x.__contains__(y) <==> y in x.

|

| __eq__(...)

| x.__eq__(y) <==> x==y

# set() 得到的也是一个集合,但是这个集合比其他形式的集合要好很多
# 比如list 之间不能直接做差
>>> a = [1,2,3]

>>> b = [3]

>>> a - b

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: unsupported operand type(s) for -: 'list' and 'list'

# set 返回的结合是一个无序的不包含重复元素的集合。
>>> a = [1,2,3,3,4,5]
>>> set(a)

set([1, 2, 3, 4, 5])

# list 结合set 使用,可以判断一个序列中比另一个序列中多哪些元素
>>> a = [1,2,3,4,5,6]

>>> b = [2,3,4,7,9]

>>> list(set(a)-set(b))

[1, 5, 6]

4.14 setattr()

setattr(...)

setattr(object, name, value)

Set a named attribute on an object; setattr(x, 'y', v) is equivalent to

``x.y = v''.

将一个属性声明的表达式用一个方法来实现,个人认为不是太好。

>>> class A():

... name = 'jia'

...

>>> a = A()

>>> a.name

'jia'

>>> setattr(a,'name','luo')

>>> a.name

'luo'

4.15 slice()

class slice(object)

| slice([start,] stop[, step])

|

| Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).

|

| Methods defined here:

|

| __cmp__(...)

| x.__cmp__(y) <==> cmp(x,y)

|

| __getattribute__(...)

| x.__getattribute__('name') <==> x.name

|

| __hash__(...)

| x.__hash__() <==> hash(x)

# 在python 内部和一些第三方库中广泛使用。
# 这里的主动切片没有什么用,list[1:2] 本身就是一个切片动作!

>>> a = [1,2,3,4,5,]

>>> a[slice(1,4,2)]

[2, 4]

>>> a

[1, 2, 3, 4, 5]

>>> a[1:4:2]

[2, 4]

>>>

4.16 sorted()
sorted(...)

sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

# 看原方法,接受参数还是比较灵活的:
返回一个排序后的列表,用于排序的元素来自iterable,后面的参数控制排序的过程。

cmp是自定义的比较函数,接受两个参数,返回负数表示第一个参数较小,返回0表示两者一样大,返回正数表示第一个参数较大。

key可以理解为每个参数的求值函数。如果提供了key,则在比较前,先对每个先用key进线求值,对结果再进行排序,但是返回的排序后的结果还是之前的值。

reverse如果是True,则按降序排列,默认是从小到大的升序。# 这样理解, sorted() 函数兼容了reversed() 函数

# 最常用的。升序排列
>>> sorted([1, 5, 3, 4, 6])

[1, 3, 4, 5, 6]
# 逆序排列
>>> sorted([1, 5, 3, 4, 6], reverse=True)

[6, 5, 4, 3, 1]
# 使用key
>>> sorted([1, 5, 3, 4, 6], key=lambda x: x%3)

[3, 6, 1, 4, 5]

# 使用cmp

>>> sorted([1, 5, 3, 4, 6], cmp=lambda x,y: x%3 - y%3)

[3, 6, 1, 4, 5]

#NOTE: 虽然cmp和key都可以实现上面的除3余数排列,但是因为cmp要对每次比较的两个元素都调用一次函数,所以,效率不如key。

5.1: staticmethod() 更多的时候是作为一个 function decorator 来使用
严格来说,sttaticmetho 是一个类。

这里简单区分一下 staticmethod, classmethod, normal method(of class).

staticmethod 静态方法, 可以通过类对象和类的实例对象访问。
# 最早是一个类, 在python 2.4 之后,作为 decorator 来使用

classmethod 类方法,类方法和静态方法都可以通过类对象和类的实例对象访问; 需要而外的类变量 cls。 (当有子类继承时,调用类方法传入的类变量cls是子类,而不是父类;
其实这是一个重写的过程,即 cls.xxx , 如果子类有 xxx, cls.xxx 就会访问子类; 如果 子类没有 xxx, 就会访问父类)。

normalmethod 普通方法, 作为类的一个方法, 需要在参数列表中加入 self, self是一个实例变量, 和调用该方法的实例有关。

一个例子:

①静态方法
>>> class Foo:
str = "I'm a static method."
def bar():
print Foo.str
bar = staticmethod(bar)
>>> Foo.bar()
I'm a static method.
②类方法
>>> class Foo:
str = "I'm a static method."
def bar(cls):
print cls.str
bar = classmethod(bar)
>>> Foo.bar()
I'm a static method.
上面的代码我们还可以写的更简便些(python2.4新语法):
①静态方法
>>> class Foo:
str = "I'm a static method."
@staticmethod
def bar():
print Foo.str
>>> Foo.bar()
I'm a static method.
②类方法
>>> class Foo:
str = "I'm a static method."
@classmethod
def bar(cls):
print cls.str
>>> Foo.bar()
I'm a static method.
5.2 str()

class str(basestring)

| str(object) -> string

|

| Return a nice string representation of the object.

| If the argument is a string, the return value is the same object.

|

| Method resolution order:

| str

| basestring

| object

|

| Methods defined here:

返回一个精确可打印的字符串,来说明object。
# “和repr(object)不同,str(object)返回的字符串不一定能被eval()执行来得到对象本身,str(object)的目标只是可打印和可读。”

# 其实这段没看懂,eval() 可以返回对象本身吗? 我这里报一个语法错误!!

>>> class A():

... name = 'jia'

...

>>> a = A()

>>> a

<__main__.A instance at 0x7fb1deed9950>

>>> repr(a)

'<__main__.A instance at 0x7fb1deed9950>'

>>> b = repr(a)

>>> c = eval(b)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "<string>", line 1

<__main__.A instance at 0x7fb1deed9950>

^

SyntaxError: invalid syntax

5.3 sum()

sum(...)

sum(sequence[, start]) -> value

Returns the sum of a sequence of numbers (NOT strings) plus the value

of parameter 'start' (which defaults to 0). When the sequence is

empty, returns start.

# 返回一个整数序列的加和
>>> sum([])

10

>>> sum([1,2,3,4,])

10

# 对iterable在start做为初值的基础上进行累加。start的默认值为0。

注意此方法不能对字符串进行相加(连接)操作,连接字符串还是用 ''.join(sequence) 好了。
#另外,sum(range(n), m)等价于 reduce(operator.add, range(n), m),

要更精确地对浮点数进行累加,请使用math.fsum()。
# 其实,这里看不懂

5.4 super()

class super(object)

| super(type) -> unbound super object

| super(type, obj) -> bound super object; requires isinstance(obj, type)

| super(type, type2) -> bound super object; requires issubclass(type2, type)

| Typical use to call a cooperative superclass method:

| class C(B):

| def meth(self, arg):

| super(C, self).meth(arg)

|

| Methods defined here:

|

| __get__(...)

| descr.__get__(obj[, type]) -> value

|

| __getattribute__(...)

| x.__getattribute__('name') <==> x.name

|

| __init__(...)

| x.__init__(...) initializes x; see x.__class__.__doc__ for signature

|

| __repr__(...)

| x.__repr__() <==> repr(x)

# test

返回一个指代type的父类或者兄弟类的对象,可以用这个对象间接地调用父类或者兄弟类的方法。在有复杂的类继承关系结构的时候,会很有用。

一个关于 super 的详解:
http://blog.csdn.net/johnsonguo/article/details/585193

5.5 tuple() 返回一个tuple 对象

class tuple(object)

| tuple() -> empty tuple

| tuple(iterable) -> tuple initialized from iterable's items

|

| If the argument is a tuple, the return value is the same object.

|

| Methods defined here:

|

| __add__(...)

| x.__add__(y) <==> x+y

|

| __contains__(...)

| x.__contains__(y) <==> y in x

>>> a = [1,2,3]

>>> tuple(a)

(1, 2, 3)

5.6 type() 判断一个对象的类型

class type(object)

| type(object) -> the object's type

| type(name, bases, dict) -> a new type

|

| Methods defined here:

|

| __call__(...)

| x.__call__(...) <==> x(...)

|

| __delattr__(...)

| x.__delattr__('name') <==> del x.name

# usage 1: 判断一个对象的类型

>>> type([1,2,3])

<type 'list'>

>>> type(1)

<type 'int'>

>>> type(0x12)

<type 'int'>

>>> type(12L)

<type 'long'>

>>> type(12f)

File "<stdin>", line 1

type(12f)

^

SyntaxError: invalid syntax

>>> type(12F)

File "<stdin>", line 1

type(12F)

^

SyntaxError: invalid syntax

>>> type(12.0)

<type 'float'>

# usage 2: 快速构建一个对象
下列等效代码:
>>>class x(object):
... a = 1

>>> x = type('x',(object,),dict(a=1))

>>> obj = x()

>>> print dir(obj)

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a']

>>> obj2 = x(a=3)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: object.__new__() takes no parameters

5.7 unichr()

unichr(...)

unichr(i) -> Unicode character

Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

# 返回一个单个字符的unicode串,此字符的unicode码值为i。对于Unicode,此函数也是ord()的反函数。i的范围由python解释器的编译环境决定。
#

>>> unichr(52)

u'4'

>>> unichr(48)

u'0'

>>> unichr(1)

u'\x01'

>>> unichr(254)

u'\xfe'

>>> unichr(97)

u'a'

# 还记得有关字符的操作码?
chr() 得到数字对应的ascii 码
ord() 得到ascii 吗对应的数字
int() 得到一个数字,字符串10进制型数字,字符串型16进制数字的10机制表示
hex() 得到一个数字的16进制表示

5.8 unicode()

class unicode(basestring)

| unicode(string [, encoding[, errors]]) -> object

|

| Create a new Unicode object from the given encoded string.

| encoding defaults to the current default string encoding.

| errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.

|

| Method resolution order:

| unicode

| basestring

| object

# 返回一个unicode 类型的字符object
# 值得研究!!

5.9 vars()

vars(...)
vars([object]) -> dictionary

Without arguments, equivalent to locals().

With an argument, equivalent to object.__dict__.

# locals(), globals()

5.10 xrange()

class xrange(object)

| xrange([start,] stop[, step]) -> xrange object

|

| Like range(), but instead of returning a list, returns an object that

| generates the numbers in the range on demand. For looping, this is

| slightly faster than range() and more memory efficient.

# 一个关于range 的优化版,效率会高一些;

5.11 zip()

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element

from each of the argument sequences. The returned list is truncated

in length to the length of the shortest argument sequence.

# 参照enumerate。 在合并两个list 时比较有用: 将两个list 中的iterm 按照位置映射起来

5.12 __import__()

__import__(...)

__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module

Import a module. The globals are only used to determine the context;

they are not modified. The locals are currently unused. The fromlist

should be a list of names to emulate ``from name import ...'', or an

empty list to emulate ``import name''.

When importing a module from a package, note that __import__('A.B', ...)

returns package A when fromlist is empty, but its submodule B when

fromlist is not empty. Level is used to determine whether to perform

absolute or relative imports. -1 is the original strategy of attempting

both absolute and relative imports, 0 is absolute, a positive number

is the number of parent directories to search relative to the current module.

# 看得不是太明白!
# 简单来说,__import__ 是被import 语句调用,代码中一般不会直接调用。

5.13 apply()

apply(...)

apply(object[, args[, kwargs]]) -> value

Call a callable object with positional arguments taken from the tuple args,

and keyword arguments taken from the optional dictionary kwargs.

Note that classes are callable, as are instances with a __call__() method.

Deprecated since release 2.3. Instead, use the extended call syntax:

function(*args, **keywords).

# TODO

5.14 buffer()

class buffer(object)

| buffer(object [, offset[, size]])

|

| Create a new buffer object which references the given object.

| The buffer will reference a slice of the target object from the

| start of the object (or at the specified offset). The slice will

| extend to the end of the target object (or with the specified size).

# 创建一个buffer 对象!

5.15 coerce()

coerce(...)

coerce(x, y) -> (x1, y1)

Return a tuple consisting of the two numeric arguments converted to

a common type, using the same rules as used by arithmetic operations.

If coercion is not possible, raise TypeError.

# TODO

5.16 intern()

intern(...)

intern(string) -> string

``Intern'' the given string. This enters the string in the (global)

table of interned strings whose purpose is to speed up dictionary lookups.

Return the string itself or the previously interned string object with the

same value.

# TODO
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: