囫圇吞棗 - Python Developer’s Handbook

前言:

這絕對不是教學文章,如果您誤入此地,建議您別浪費時間;我已經事先告訴您了!
這本書有點舊,所以用最新的環境測過,以及自己亂寫範例;一定要看官方文件,否則絕對會後悔!

環境:

Python 2.6.4 (r264:75706, Nov 30 2009, 11:30:42)
[GCC 4.2.1 20070719  [FreeBSD]] on freebsd8
Type "help", "copyright", "credits" or "license" for more information.
>>>

Built-in Functions

abs(x) 回傳絕對值

範例:

>>> print(abs(1), abs(-100), abs(-4))
(1, 100, 4)

all(iterable) 如果所有 iterable 裡面的 element 都是 true(或是空 iterable),則回傳 True,否則回傳 False (> Python 2.5)

範例:

>>> mylist = ['aa', 'bb', 'cc']
>>> all(mylist)
True
>>> mylist2 = ['aa', '', 'cc']
>>> all(mylist2)
False
>>> mylist3 = []
>>> all(mylist3)
True

any(iterable) 若 iterable 的 element 其中有一為 true 即回傳 True,否則回傳 False (> Python 2.5)

範例:

>>> mylist = ['aa', 'bb', 'cc']
>>> any(mylist)
True
>>> mylist2 = ['aa', '', 'cc']
>>> any(mylist2)
True
>>> mylist3 = []
>>> any(mylist3)
False
>>>

basestring() 查出是不是 str or unicode,是則回傳 True,否則回傳 false (> Python 2.3)

範例:

>>> aa = u'aa'
>>> isinstance(aa, basestring)
True
>>> bb = ['aa', 'bb']
>>> isinstance(bb, basestring)
False
>>>

bin(x) 將正整數轉為 binary string (> Python 2.6)

範例:

>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(100)
'0b1100100'
>>> bin(100)

bool([x]) 將值轉為 True or False,(> Python 2.2.1)

範例:

>>> bool('aa')
True
>>> bool('0')
True
>>> bool('')
False
>>> bool()
False
>>> bool([])
False
>>>

callable(object) 如果 callable 就回傳 True,否則為 False;但不代表 callable 的目標程式不會 fail。

範例:

>>> callable('aa')
False
>>> def hello():
...     print('hello')
...
>>> callable(hello)
True
>>> def hello2():
...     print(ooxx)
...
>>> callable(hello2)
True  #這裡 return True,但是要注意 hello2 的 ooxx 並沒 defined 喔
>>> hello2()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in hello2
NameError: global name 'ooxx' is not defined
>>>

chr (i) 回傳 ASCII code 是 0-255 的字元符號,超過這個範圍就會失敗(也請同步看一下 unichr() 函式)

範例:

>>> chr(80)
'P'
>>> chr(256)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ValueError: chr() arg not in range(256)
>>>

classmethod (function) 回傳一個 calss 的 method,這是個 function decorator,讓 class 或一個已存在的 instance 可以被呼叫。強烈建議到官網文件查找一下沿革及完整用法(如果要用類似其他語言的 static method,請使用 staticmethod) (> Python 2.2)

範例:

>>> class Hello:
...     @classmethod
...     def say(self, who):
...             print('hello, %s' % who)
...
>>> Hello.say('pct')  # 沒有先實體化就來呼叫
hello, pct
>>> class Hello2:
...     def say(self, who):
...             print('hello, %s' % who)
...
>>> Hello2.say('pct')
>>> #但是以下都是先實體化,所以本來就可以呼叫
>>> Hello().say('pct')
hello, pct
>>> Hello2().say('pct')
hello, pct
>>>

cmp(x, y) 比較 x, y 的值並回傳。x < y 回傳 -1 ; x == y 回傳 0 ; x > y 回傳 1

範例:

>>> cmp(1, 2)
-1
>>> cmp(2, 1)
1
>>> cmp(1, 1)
0
>>> cmp('1', '1')
0
>>> cmp('1', '2')
-1
>>> cmp('3', '2')
1
>>> cmp('aa', '2')
1

compile(source, filename, mode[, flags[, dont_inherit]]) 將 source compile 成 code 或 AST object,可被 exec 使用或 eval 拿來呼叫;這邊還是要多看其他範例來練習 (> Python 2.3)

範例:

>>> code = compile('print("hello, pct")', '', 'exec')
>>> exec(code)
hello, pct
>>> code2 = compile('1+2+3', '', 'eval')
>>> eval(code2)
6

complex([real[, imag]]) 建立複數,詳細說明還是看官網

範例:

>>> complex(4,5)
(4+5j)

delattr(object, name) 刪除字串或是物件裡面的 attribute,與 setattr 對應

範例:

>>> class Person: pass
...
>>> pct = Person()
>>> pct.bug = 1
>>> pct.bug
1
>>> delattr(pct, 'bug')
>>> print pct
>>> pct.bug
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: Person instance has no attribute 'bug'
>>>

dict([arg]) 建立 dictionary

範例:

>>> aa = ['a', 'b']
>>> bb = ['c', 'd']
>>> dict(aa)
>>> dict([aa,bb])
{'a': 'b', 'c': 'd'}
>>> dict(a=2, b=3)
{'a': 2, 'b': 3}
>>>

dir([object]) 列出 object 的所有 attribute 名稱,如果不加參數,則會列出所有 local scope 的名稱

範例:

>>> aa = {}
>>> dir(aa)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>

divmod(a, b) 取出商數及餘數

範例:

>>> divmod(101, 4)
(25, 1)
>>> (101 // 4, 101 % 4)
(25, 1)
>>>

enumerate(sequence[, start=0]) 回傳 enumerate object,請直接看範例 (> Python 2.3)

範例:

>>> aa = enumerate(('aa', 'bb', 'cc', 'dd', 'ee'))
>>> for i, num in aa:
...     print i, num
...
0 aa
1 bb
2 cc
3 dd
4 ee
>>>

eval(expression[, globals[, locals]]) Evaluate expression

範例:

>>> code = '1+2+3'
>>> eval(code)
6

execfile(filename[, globals[, locals]]) 執行某個檔案的內容,似 exec,只是 exec 是輸入內容當參數,

範例:

>>> execfile('hello.py')
hello, pct

file(filename[, mode[, bufsize]]) file object 的 Constructor,參數同 open()

範例:

>>> aa = file('hello.py', 'r')
>>> aa.read()
"#!/usr/bin/env python\n\nprint('hello, pct')\n"
>>>

filter(function, iterable) 自定函式過濾 list 的 elements

範例:

>>> def check(num):
...     return (num % 2)
...
>>> filter(check, [1,2,3,4,5,6,7,8,9,0])
[1, 3, 5, 7, 9]
>>>

float([x]) 轉數字成浮點數

範例:

>>> float('-234')
-234.0
>>> float(-234)
-234.0
>>>

待續...

format(value[, format_spec])

Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language.

Note format(value, format_spec) merely calls value.__format__(format_spec). New in version 2.6.

frozenset([iterable])

Return a frozenset object, optionally with elements taken from iterable. The frozenset type is described in Set Types — set, frozenset.

For other containers see the built in dict, list, and tuple classes, and the collections module.

New in version 2.4.

getattr(object, name[, default])

Return the value of the named attributed of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

globals()

Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).

hasattr(object, name)

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an exception or not.)

hash(object)

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

help([object])

Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

This function is added to the built-in namespace by the site module.

New in version 2.2.

hex(x)

Convert an integer number (of any size) to a hexadecimal string. The result is a valid Python expression.

Note To obtain a hexadecimal string representation for a float, use the float.hex() method. Changed in version 2.4: Formerly only returned an unsigned literal.

id(object)

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object.

input([prompt])

Equivalent to eval(raw_input(prompt)).

Warning This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.) If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

Consider using the raw_input() function for general input from users.

int([x[, base]])

Convert a string or number to a plain integer. If the argument is a string, it must contain a possibly signed decimal number representable as a Python integer, possibly embedded in whitespace. The base parameter gives the base for the conversion (which is 10 by default) and may be any integer in the range [2, 36], or zero. If base is zero, the proper radix is determined based on the contents of string; the interpretation is the same as for integer literals. (See Numeric literals.) If base is specified and x is not a string, TypeError is raised. Otherwise, the argument may be a plain or long integer or a floating point number. Conversion of floating point numbers to integers truncates (towards zero). If the argument is outside the integer range a long object will be returned instead. If no arguments are given, returns 0.

The integer type is described in Numeric Types — int, float, long, complex.

isinstance(object, classinfo)

Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct or indirect) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

Changed in version 2.2: Support for a tuple of type information was added.

issubclass(class, classinfo)

Return true if class is a subclass (direct or indirect) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

Changed in version 2.3: Support for a tuple of type information was added.

iter(o[, sentinel])

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the __iter__() method), or it must support the sequence protocol (the __getitem__() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until “STOP” is reached:

with open(“mydata.txt”) as fp:
for line in iter(fp.readline, “STOP”):
process_line(line)

New in version 2.2.

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

list([iterable])

Return a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list(‘abc’) returns [‘a’, ‘b’, ‘c’] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, [].

list is a mutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, buffer, xrange. For other containers see the built in dict, set, and tuple classes, and the collections module.

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

long([x[, base]])

Convert a string or number to a long integer. If the argument is a string, it must contain a possibly signed number of arbitrary size, possibly embedded in whitespace. The base argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L.

The long type is described in Numeric Types — int, float, long, complex.

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. If one iterable is shorter than another it is assumed to be extended with None items. If function is None, the identity function is assumed; es (a kind of transpose operation). The iterable arguments may be a sequence or any iterable object; the result is always a list return the largest item of a non-empty iterable (such as a string, tuple or list). With more than one argument, return the largts.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if snc)).

Changed in version 2.5: Added support for the optional key argument.

min(iterable[, args...][, key])

With a single argums.

The optional key argument specifies a one-argument ordering function like that used for list.sort(). The key argument, if sueyword form (for example, min(a,b,c,key=func)).

Changed in version 2.5: Added support for the optional key argument.

next(iterext item from the iterator by calling its next() method. If default is given, it is returned if the iterator is exhausted, otherersion 2.6.

object()

Return a new featureless object. object is a base for all new style classes. It has the methods that are c This function does not accept any arguments. Formerly, it accepted arguments but ignored them.

oct(x)

Convert an integer numbeal string. The result is a valid Python expression.

Changed in version 2.4: Formerly only returned an unsigned literal.

open(f described in section File Objects. If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to uvoking the file constructor directly.

The first two arguments are the same as for stdio‘s fopen(): filename is the file name ring indicating how the file is to be opened.

The most commonly-used values of mode are ‘r’ for reading, ‘w’ for writing (truncating the file if it already exists), and ‘a’ for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to ‘r’. The default is to use text mode, which may convert ‘n’ characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append ‘b’ to the mode value to open the file in binary mode, which will improve portability. (Appending ‘b’ is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below fomode.

The optional bufsize argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any eans use a buffer of (approximately) that size. A negative bufsize means to use the system default, which is usually line bufferult is used. [2]

Modes ‘r+’, ‘w+’ and ‘a+’ open the file for updating (note that ‘w+’ truncates the file). Append ‘b’ to the mohis distinction, adding the ‘b’ has no effect.

In addition to the standard fopen() values mode may be ‘U’ or ‘rU’. Python is usersal newline support; supplying ‘U’ opens the file as a text file, but lines may be terminated by any of the following: the Unintion ‘r’, or the Windows convention ‘rn’. All of these external representations are seen as ‘n’ by the Python program. If Pupport a mode with ‘U’ is the same as normal text mode. Note that file objects so opened also have an attribute called newlines lines have yet been seen), ‘n’, ‘r’, ‘rn’, or a tuple containing all the newline types seen.

Python enforces that the mode,with ‘r’, ‘w’ or ‘a’.

Python provides many file handling modules including fileinput, os, os.path, tempfile, and shutil.

Changon on first letter of mode string introduced.

ord(c)

Given a string of length one, return an integer representing the Unicode c byte when the argument is an 8-bit string. For example, ord(‘a’) returns the integer 97, ord(u’u2020’) returns 8224. This is tngs and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the charact [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.

pow(x, y[, z])

Return x to the power puted more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.

Thules for binary arithmetic operators apply. For int and long int operands, the result has the same type as the operands (after cl arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. (ThIn Python 2.1 and before, if both arguments were of integer types and the second argument was negative, an exception was raised.ent is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negatifore, floating 3-argument pow() returned platform-dependent results depending on floating-point rounding accidents.)

range([start], stop[, step])

This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]

raw_input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"
If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features.

reduce(function, iterable example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated valuealue from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

reloadorted module. The argument must be a module object, so it must have been successfully imported before. This is useful if you havreload(module) is executed:

Python modules’ code is recompiled and the module-level code reexecuted, defining a new set of obes in the module’s dictionary. The init function of extension modules is not called a second time. As with all other objects ijects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to an the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desir module is syntactically correct but its initialization fails, the first import statement for it does not bind its name locally,itialized) module object in sys.modules. To reload the module you must first import it again (this will bind the name to the parodule does not define a name that was defined by the old version, the old definition remains. This feature can be used to the mot maintains a global table or cache of objects — with a try statement it can test for the table’s presence and skip its init cache except NameError:

cache = {}

It is legal though generally not very useful to reload built-in or dynamically loaded mtin__. In many cases, however, extension modules are not designed to be initialized more than once, and may fail in arbitrary wamports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objectmodule.*name*) instead.

If a module instantiates instances of a class, reloading the module that defines the class does not aff” they continue to use the old class definition. The same is true for derived classes.

repr(object)

Return a string containing This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an a string enclosed in angle brackets that contains the name of the type of the object together with additional information oftenress of the object. A class can control what this function returns for its instances by defining a __repr__() method.

reversed(s be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() me.6: Added the possibility to write a custom __reversed__() method.

round(x[, n])

Return the floating point value x rounded to n n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to tqually close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

set([iterable])

Return described in Set Types — set, frozenset.

For other containers see the built in dict, list, and tuple classes, and the collectsetattr(object, name, value) This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, ‘foobact representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice obart, stop and step which merely return the argument values (or their default). They have no other explicit functionality; howevegenerated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() forod (described in section Mutable Sequence Types).

cmp specifies a custom comparison function of two arguments (iterable elementeturn a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or large.lower(), y.lower()). The default value is None.

key specifies a function of one argument that is used to extract a comparison None.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In grocesses are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list h each element only once. To convert an old-style cmp function to a key function, see the CmpToKey recipe in the ASPN cookbook. taticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

Ithe class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class.

Static methods in Java or C++. For a more advanced concept, see classmethod() in this section.

For more information on static methods, consult th the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator sy an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always atings see Sequence Types — str, unicode, list, tuple, buffer, xrange which describes sequence functionality (strings are sequene string-specific methods described in the String Methods section. To output formatted strings use template strings or the % ope section. See also unicode().

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns thealling ‘’.join(sequence). Note that sum(range(n), m) is equivalent to reduce(operator.add, range(n), m) To add floating point vaNew in version 2.3.

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling clasaccessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that attribute of the type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic anditance hierarchy is updated.

If the second argument is omitted, the super object returned is unbound. If the second argument isst be true. If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods).

Note supeor new-style classes. There are two typical use cases for super. In a class hierarchy with single inheritance, super can be used without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other pr case is to support cooperative multiple inheritance in a dynamic execution environment. This use case is unique to Python and ied languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” whereent the same method. Good design dictates that this method have the same calling signature in every case (because the order of c are unknown prior to runtime).

For both use cases, a typical superclass call looks like this:

class C(B):
def method(selfuper(C, self).method(arg)

Note that super() is implemented as part of the binding process for explicit dotted attribute lookups ). It does so by implementing its own __getattribute__() method for searching classes in a predictable order that supports coopeitance. Accordingly, super() is undefined for implicit lookups using statements or operators such as super()[name].

Also note tt limited to use inside methods. The two argument form specifies the arguments exactly and makes the appropriate references.

Neame and in the same order as iterable‘s items. iterable may be a sequence, a container that supports iteration, or an iteratorurned unchanged. For instance, tuple(‘abc’) returns (‘a’, ‘b’, ‘c’) and tuple([1, 2, 3]) returns (1, 2, 3). If no argument is giy tuple, ().

tuple is an immutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, buffer, xranged the collections module.

type(object)

Return the type of an object. The return value is a type object. The isinstance() built-for testing the type of an object.

With three arguments, type() functions as a constructor as detailed below.

type(name, bases form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes they is the namespace containing definitions for class body and becomes the __dict__ attribute. For example, the following two statical type objects:

>>> class X(object):
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))
New in version 2.2.

unichr(i one character whose Unicode code is the integer i. For example, unichr(97) returns the string u’a’. This is the inverse of ord(ured – it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF]. ValueError is raised otherwise. For ASCII and 8-bit strings seding[, errors]]])

Return the Unicode string version of object using one of the following modes:

If encoding and/or errors are ge the object which can either be an 8-bit string or a character buffer using the codec for encoding. The encoding parameter is apError is raised. Error handling is done according to errors; this specifies the treatment of characters which are invalid in thlueError is raised on errors, while a value of ‘ignore’ causes errors to be silently ignored, and a value of ‘replace’ causes thU+FFFD, to be used to replace input characters which cannot be decoded. See also the codecs module.

If no optional parameters a) will mimic the behaviour of str() except that it returns Unicode strings instead of 8-bit strings. More precisely, if object i will return that Unicode string without any additional decoding applied.

For objects which provide a __unicode__() method, it guments to create a Unicode string. For all other objects, the 8-bit string version or representation is requested and then conv string using the codec for the default encoding in ‘strict’ mode.

For more information on Unicode strings see Sequence Types âe which describes sequence functionality (Unicode strings are sequences), and also the string-specific methods described in thut formatted strings use template strings or the % operator described in the String Formatting Operations section. In addition see also str().

New in version 2.0.

Changed in version 2.2: Support for __unicode__() added.

vars([object])

Without an argumen module, class or class instance object as argument (or anything else that has a __dict__ attribute), return that attribute.

No step]) This function is very similar to range(), but returns an “xrange object” instead of a list. This is an opaque sequenalues as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is min when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements aetail: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementationents to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a the itertools module: islice(count(start, step), (stop-start+step-1)//step).

zip([iterable, ...])

This function returns a liste i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the snce. When there are multiple arguments which are all of the same length, zip() is similar to map() with an initial argument of N it returns a list of 1-tuples. With no arguments, it returns an empty list.

The left-to-right evaluation order of the iterable possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

zip() in conjunction with the * od = zip(x, y) >>> zipped [(1, 4), (2, 5), (3, 6)] >>> x2, y2 = zip(*zipped) >>> x == list(x2) and y == list(y2) True New in versired at least one argument and zip() raised a TypeError instead of returning an empty list.

__import__(name[, globals[, locals[]]]]) Note This is an advanced function that is not needed in everyday Python programming. This function is invoked by the impor.__import__) in order to change semantics of the import statement, but nowadays it is usually simpler to use import hooks (see Ps rare, except in cases where you want to import a module whose name is only known at runtime.

The function imports the module using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level speciolute or relative imports. The default is -1 which indicates both absolute and relative imports will be attempted. 0 means only sitive values for level indicate the number of parent directories to search relative to the directory of the module calling __imme variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not theen a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam resultsspam = __import__(‘spam’, globals(), locals(), [], -1) The statement import spam.ham results in this call:

spam = __import__(‘sage’], -1) eggs = _temp.eggs saus = _temp.sausage Here, the spam.ham module is returned from __import__(). From this object, theort are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) _import__() and then look it up in sys.modules:

>>> import sys
>>> name = 'foo.bar.baz'
>>> __import__(name)
<module 'foo' from
Changed in version 2.5: The level parameter was added.

Changed in version 2.5: Keyword support for parameters was added.

3. Nions There are several built-in functions that are no longer essential to learn, know or use in modern Python programming. They ackwards compatibility with programs written for older versions of Python.

Python programmers, trainers, students and book writhod, or a class object) and the args argument must be a sequence. The function is called with args as the argument list; the numtuple. If the optional keywords argument is present, it must be a dictionary whose keys are strings. It specifies keyword argumeply() is different from just calling function(args), since in that case there is always exactly one argument. The use of apply()ted since version 2.3: Use the extended call syntax with *args and **keywords instead.

buffer(object[, offset[, size]]) The obj an object that supports the buffer call interface (such as strings, arrays, and buffers). A new buffer object will be created we beginning of object (or from the specified offset). The slice will extend to the end of object (or will have a length given bytuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations.tring) Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. erformance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisonn be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically internd to hold module, class or instance attributes have interned keys.

Changed in version 2.3: Interned strings are not immortal (ld before); you must keep a reference to the return value of intern() around to benefit from it.

內容目錄

上一個主題

Python TDD Notes

下一個主題

囫圇吞棗 - Python 高級編程

本頁