程式開發常見問答集

常見問題

是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器?

有的。

下面描述了幾個 Python 除錯器,內建函式breakpoint() 允許你進入其中任何一個。

pdb 模組是一個簡單但足夠的 Python 控制台模式除錯器。它是標準 Python 函式庫的一部分,並記錄在函式庫參考手冊中。你也可以參考 pdb 的程式碼作為範例來編寫自己的除錯器。

IDLE 交互式開發環境,它是標準 Python 發行版的一部分(通常作為Tools/scripts/idle3 提供),包括一個圖形除錯器。

PythonWin 是一個 Python IDE,它包含一個基於 pdb 的 GUI 除錯器。 PythonWin 除錯器為斷點著色並具有許多很酷的功能,例如除錯非 PythonWin 程式。 PythonWin 作為pywin32 專案的一部分和作為ActivePython 的一部分發佈。

Eric 是一個基於 PyQt 和 Scintilla 編輯元件所建構的 IDE。

trepan3k 是一個類似 gdb 的除錯器。

Visual Studio Code 是一個整合了版本控制軟體與除錯工具的 IDE。

有數個商業化Python整合化開發工具包含圖形除錯功能。這些包含:

有沒有工具能夠幫忙找 bug 或執行靜態分析?

有的。

PylintPyflakes 進行基本檢查以幫助你儘早抓出錯誤。

靜態型別檢查器,例如MypyPyrePytype 可以檢查 Python 原始碼中的型別提示。

如何從 Python 腳本建立獨立的二進位檔案?

You don't need the ability to compile Python to C code if all you want is astand-alone program that users can download and run without having to installthe Python distribution first. There are a number of tools that determine theset of modules required by a program and bind these modules together with aPython binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree asTools/freeze.It converts Python byte code to C arrays; with a C compiler you canembed all your modules into a new program, which is then linked with thestandard Python modules.

It works by scanning your source recursively for import statements (in bothforms) and looking for the modules in the standard Python path as well as in thesource directory (for built-in modules). It then turns the bytecode for moduleswritten in Python into C code (array initializers that can be turned into codeobjects using the marshal module) and creates a custom-made config file thatonly contains those built-in modules which are actually used in the program. Itthen compiles the generated C code and links it with the rest of the Pythoninterpreter to form a self-contained binary which acts exactly like your script.

以下套件可以幫助建立 console 和 GUI 可執行檔案:

Python 程式碼是否有編碼標準或風格指南?

是的。標準函式庫模組所需的編碼風格稱為PEP 8

核心語言

為什麼當變數有值時,我仍得到錯誤訊息 UnboundLocalError?

It can be a surprise to get theUnboundLocalError in previously workingcode when it is modified by adding an assignment statement somewhere inthe body of a function.

這段程式碼:

>>>x=10>>>defbar():...print(x)...>>>bar()10

可以執行,但是這段程式:

>>>x=10>>>deffoo():...print(x)...x+=1

導致UnboundLocalError

>>>foo()Traceback (most recent call last):...UnboundLocalError:local variable 'x' referenced before assignment

This is because when you make an assignment to a variable in a scope, thatvariable becomes local to that scope and shadows any similarly named variablein the outer scope. Since the last statement in foo assigns a new value tox, the compiler recognizes it as a local variable. Consequently when theearlierprint(x) attempts to print the uninitialized local variable andan error results.

在上面的範例中,你可以透過將其聲明為全域變數來存取外部範圍變數:

>>>x=10>>>deffoobar():...globalx...print(x)...x+=1...>>>foobar()10

This explicit declaration is required in order to remind you that (unlike thesuperficially analogous situation with class and instance variables) you areactually modifying the value of the variable in the outer scope:

>>>print(x)11

你可以使用nonlocal 關鍵字在巢狀作用域內做類似的事情:

>>>deffoo():...x=10...defbar():...nonlocalx...print(x)...x+=1...bar()...print(x)...>>>foo()1011

Python 的區域變數和全域變數有什麼規則?

In Python, variables that are only referenced inside a function are implicitlyglobal. If a variable is assigned a value anywhere within the function's body,it's assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment's consideration explains this. Onone hand, requiringglobal for assigned variables provides a baragainst unintended side-effects. On the other hand, ifglobal was requiredfor all global references, you'd be usingglobal all the time. You'd haveto declare as global every reference to a built-in function or to a component ofan imported module. This clutter would defeat the usefulness of theglobaldeclaration for identifying side-effects.

為什麼以不同的值在迴圈中定義的 lambda 都回傳相同的結果?

假設你使用 for 迴圈來定義幾個不同的 lambda(甚至是普通函式),例如:

>>>squares=[]>>>forxinrange(5):...squares.append(lambda:x**2)

這會提供一個包含五個計算x**2 的 lambda 串列。你可能會預期在呼叫它時,它們會分別回傳014916,然而當你實際嘗試你會發現它們都回傳16

>>>squares[2]()16>>>squares[4]()16

發生這種情況是因為x 不是 lambda 的局部變數,而是在外部作用域中定義的,且是在呼叫 lambda 時才會存取它,並非於定義時就會存取。在迴圈結束時,x 的值為4,因此所有函式都回傳4**2,即為16。你還可以透過更改x 的值來驗證這一點,並查看 lambda 運算式的結果如何變化:

>>>x=8>>>squares[2]()64

為了避免這種情況,你需要將值保存在 lambda 的局部變數中,這樣它們就不會依賴於全域x 的值:

>>>squares=[]>>>forxinrange(5):...squares.append(lambdan=x:n**2)

Here,n=x creates a new variablen local to the lambda and computedwhen the lambda is defined so that it has the same value thatx had atthat point in the loop. This means that the value ofn will be0in the first lambda,1 in the second,2 in the third, and so on.Therefore each lambda will now return the correct result:

>>>squares[2]()4>>>squares[4]()16

請注意,此行為並非 lambda 所特有,也適用於常規函式。

如何跨模組共享全域變數?

The canonical way to share information across modules within a single program isto create a special module (often called config or cfg). Just import the configmodule in all modules of your application; the module then becomes available asa global name. Because there is only one instance of each module, any changesmade to the module object get reflected everywhere. For example:

config.py:

x=0# 'x' 配置設定的預設值

mod.py:

importconfigconfig.x=1

main.py:

importconfigimportmodprint(config.x)

請注意,出於同樣的原因,使用模組也是實作單例設計模式的基礎。

在模組中使用 import 的「最佳實踐」有哪些?

In general, don't usefrommodulenameimport*. Doing so clutters theimporter's namespace, and makes it much harder for linters to detect undefinednames.

Import modules at the top of a file. Doing so makes it clear what other modulesyour code requires and avoids questions of whether the module name is in scope.Using one import per line makes it easy to add and delete module imports, butusing multiple imports per line uses less screen space.

It's good practice if you import modules in the following order:

  1. 標準函式庫模組 —— 例如sysosargparsere

  2. third-party library modules (anything installed in Python's site-packagesdirectory) -- e.g.dateutil,requests,PIL.Image

  3. 本地開發的模組

It is sometimes necessary to move imports to a function or class to avoidproblems with circular imports. Gordon McMillan says:

Circular imports are fine where both modules use the "import <module>" formof import. They fail when the 2nd module wants to grab a name out of thefirst ("from module import name") and the import is at the top level. That'sbecause names in the 1st are not yet available, because the first module isbusy importing the 2nd.

In this case, if the second module is only used in one function, then the importcan easily be moved into that function. By the time the import is called, thefirst module will have finished initializing, and the second module can do itsimport.

It may also be necessary to move imports out of the top level of code if some ofthe modules are platform-specific. In that case, it may not even be possible toimport all of the modules at the top of the file. In this case, importing thecorrect modules in the corresponding platform-specific code is a good option.

Only move imports into a local scope, such as inside a function definition, ifit's necessary to solve a problem such as avoiding a circular import or aretrying to reduce the initialization time of a module. This technique isespecially helpful if many of the imports are unnecessary depending on how theprogram executes. You may also want to move imports into a function if themodules are only ever used in that function. Note that loading a module thefirst time may be expensive because of the one time initialization of themodule, but loading a module multiple times is virtually free, costing only acouple of dictionary lookups. Even if the module name has gone out of scope,the module is probably available insys.modules.

為什麼物件之間共享預設值?

這種類型的錯誤通常會困擾新手程式員。像是這個函式:

deffoo(mydict={}):# 危險:所有呼叫共享對字典的參照...計算一些東西...mydict[key]=valuereturnmydict

第一次呼叫此函式時,mydict 包含一個項目。第二次後mydict 包含兩個項目,因為當foo() 開始執行時,mydict 以其中已有的項目開始。

It is often expected that a function call creates new objects for defaultvalues. This is not what happens. Default values are created exactly once, whenthe function is defined. If that object is changed, like the dictionary in thisexample, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, andNone,are safe from change. Changes to mutable objects such as dictionaries, lists,and class instances can lead to confusion.

由於這個特性,不使用可變物件作為預設值是一個很好的程式設計習慣,而是應使用None 作為預設值,並在函式內部檢查參數是否為None,再建立一個新的串列/字典/或其他東西。例如,不要這樣寫:

deffoo(mydict={}):...

而是寫成:

deffoo(mydict=None):ifmydictisNone:mydict={}# 為區域命名空間建立一個新字典

This feature can be useful. When you have a function that's time-consuming tocompute, a common technique is to cache the parameters and the resulting valueof each call to the function, and return the cached value if the same value isrequested again. This is called "memoizing", and can be implemented like this:

# 呼叫者只能提供兩個參數,並選擇性地透過關鍵字傳遞 _cachedefexpensive(arg1,arg2,*,_cache={}):if(arg1,arg2)in_cache:return_cache[(arg1,arg2)]# Calculate the valueresult=...expensivecomputation..._cache[(arg1,arg2)]=result# 將結果存儲在快取中returnresult

你可以使用包含字典的全域變數而不是預設值;這取決於喜好。

How can I pass optional or keyword parameters from one function to another?

Collect the arguments using the* and** specifiers in the function'sparameter list; this gives you the positional arguments as a tuple and thekeyword arguments as a dictionary. You can then pass these arguments whencalling another function by using* and**:

deff(x,*args,**kwargs):...kwargs['width']='14.3c'...g(x,*args,**kwargs)

引數 (arguments) 和參數 (parameters) 有什麼區別?

參數由出現在函式定義中的名稱定義,而引數是呼叫函式時實際傳遞給函式的值。參數定義函式可以接受的引數種類。例如,給定以下函式定義:

deffunc(foo,bar=None,**kwargs):pass

foobarkwargsfunc 的參數。然而當呼叫func 時,例如:

func(42,bar=314,extra=somevar)

42314somevar 是引數。

為什麼更改串列 'y' 也會更改串列 'x'?

如果你寫了像這樣的程式碼:

>>>x=[]>>>y=x>>>y.append(10)>>>y[10]>>>x[10]

你可能想知道為什麼將一個元素附加到y 時也會改變x

產生這個結果的原因有兩個:

  1. Variables are simply names that refer to objects. Doingy=x doesn'tcreate a copy of the list -- it creates a new variabley that refers tothe same objectx refers to. This means that there is only one object(the list), and bothx andy refer to it.

  2. list 是mutable,這意味著你可以變更它們的內容。

在呼叫append() 之後,可變物件的內容從[] 變成了[10]。由於這兩個變數都參照同一個物件,因此使用任一名稱都可以存取修改後的值[10]

如果我們改為賦予一個不可變物件給x

>>>x=5# 整數為不可變的>>>y=x>>>x=x+1# 5 不可變,在這邊會建立一個新物件>>>x6>>>y5

we can see that in this casex andy are not equal anymore. This isbecause integers areimmutable, and when we dox=x+1 we are notmutating the int5 by incrementing its value; instead, we are creating anew object (the int6) and assigning it tox (that is, changing whichobjectx refers to). After this assignment we have two objects (the ints6 and5) and two variables that refer to them (x now refers to6 buty still refers to5).

Some operations (for exampley.append(10) andy.sort()) mutate theobject, whereas superficially similar operations (for exampley=y+[10]andsorted(y)) create a new object. In general in Python (and in all casesin the standard library) a method that mutates an object will returnNoneto help avoid getting the two types of operations confused. So if youmistakenly writey.sort() thinking it will give you a sorted copy ofy,you'll instead end up withNone, which will likely cause your program togenerate an easily diagnosed error.

However, there is one class of operations where the same operation sometimeshas different behaviors with different types: the augmented assignmentoperators. For example,+= mutates lists but not tuples or ints (a_list+=[1,2,3] is equivalent toa_list.extend([1,2,3]) and mutatesa_list, whereassome_tuple+=(1,2,3) andsome_int+=1 createnew objects).

換句話說:

  • If we have a mutable object (list,dict,set,etc.), we can use some specific operations to mutate it and all the variablesthat refer to it will see the change.

  • If we have an immutable object (str,int,tuple,etc.), all the variables that refer to it will always see the same value,but operations that transform that value into a new value always return a newobject.

If you want to know if two variables refer to the same object or not, you canuse theis operator, or the built-in functionid().

如何編寫帶有輸出參數的函式(透過傳參照呼叫 (call by reference))?

請記住,在 Python 中引數是透過賦值傳遞的。由於賦值只是建立對物件的參照,因此呼叫者和被呼叫者的引數名稱之間沒有別名,因此本身沒有傳參照呼叫。你可以透過多種方式實作所需的效果。

  1. 透過回傳結果的元組:

    >>>deffunc1(a,b):...a='new-value'# a 和 b 為區域名稱...b=b+1# 賦值到新物件...returna,b# 回傳新值...>>>x,y='old-value',99>>>func1(x,y)('new-value', 100)

    這幾乎都會是最清楚的方案。

  2. 透過使用全域變數。這不是執行緒安全的,所以不推薦。

  3. 透過傳遞一個可變的(可於原地 (in-place) 改變的)物件:

    >>>deffunc2(a):...a[0]='new-value'# 'a' 參照一個可變的串列...a[1]=a[1]+1# 改變共享的物件...>>>args=['old-value',99]>>>func2(args)>>>args['new-value', 100]
  4. 透過傳入一個發生改變的字典:

    >>>deffunc3(args):...args['a']='new-value'# args 是可變字典...args['b']=args['b']+1# 原地改變它...>>>args={'a':'old-value','b':99}>>>func3(args)>>>args{'a': 'new-value', 'b': 100}
  5. 或者在類別實例中捆綁值:

    >>>classNamespace:...def__init__(self,/,**args):...forkey,valueinargs.items():...setattr(self,key,value)...>>>deffunc4(args):...args.a='new-value'# args 是可變命名空間...args.b=args.b+1# 原地改變物件...>>>args=Namespace(a='old-value',b=99)>>>func4(args)>>>vars(args){'a': 'new-value', 'b': 100}

    幾乎不會有要讓事情變得如此複雜的充分理由。

你最好的選擇是回傳一個包含多個結果的元組。

你如何在 Python 中建立高階函式?

你有兩種選擇:可以使用巢狀作用域,也可以使用可呼叫物件。例如,假設你想定義linear(a,b),它會回傳a*x+b 計算值的函式f(x)。使用巢狀作用域:

deflinear(a,b):defresult(x):returna*x+breturnresult

或者使用可呼叫物件:

classlinear:def__init__(self,a,b):self.a,self.b=a,bdef__call__(self,x):returnself.a*x+self.b

在這兩種情況下:

taxes=linear(0.3,2)

給定一個可呼叫物件,其中taxes(10e6)==0.3*10e6+2

The callable object approach has the disadvantage that it is a bit slower andresults in slightly longer code. However, note that a collection of callablescan share their signature via inheritance:

classexponential(linear):# __init__ inheriteddef__call__(self,x):returnself.a*(x**self.b)

物件可以封裝多個方法的狀態:

classcounter:value=0defset(self,x):self.value=xdefup(self):self.value=self.value+1defdown(self):self.value=self.value-1count=counter()inc,dec,reset=count.up,count.down,count.set

這裡的inc()dec()reset() 就像共享相同計數變數的函式一樣。

如何在 Python 中複製物件?

In general, trycopy.copy() orcopy.deepcopy() for the general case.Not all objects can be copied, but most can.

Some objects can be copied more easily. Dictionaries have acopy()method:

newdict=olddict.copy()

序列可以透過切片 (slicing) 複製:

new_l=l[:]

如何找到物件的方法或屬性?

For an instancex of a user-defined class,dir(x) returns an alphabetizedlist of the names containing the instance attributes and methods and attributesdefined by its class.

我的程式碼如何發現物件的名稱?

Generally speaking, it can't, because objects don't really have names.Essentially, assignment always binds a name to a value; the same is true ofdef andclass statements, but in that case the value is acallable. Consider the following code:

>>>classA:...pass...>>>B=A>>>a=B()>>>b=a>>>print(b)<__main__.A object at 0x16D07CC>>>>print(a)<__main__.A object at 0x16D07CC>

Arguably the class has a name: even though it is bound to two names and invokedthrough the nameB the created instance is still reported as an instance ofclassA. However, it is impossible to say whether the instance's name isa orb, since both names are bound to the same value.

Generally speaking it should not be necessary for your code to "know the names"of particular values. Unless you are deliberately writing introspectiveprograms, this is usually an indication that a change of approach might bebeneficial.

在 comp.lang.python 中,Fredrik Lundh 曾針對這個問題給出了一個極好的比喻:

就像你在門廊上發現的那隻貓的名字一樣:貓(物件)本身不能告訴你它的名字,它也不關心 - 所以找出它叫什麼的唯一方法是詢問所有鄰居(命名空間)是否是他們的貓(物件)...

....如果你發現它有很多名字,或者根本沒有名字,請不要感到驚訝!

逗號運算子的優先級是什麼?

Comma is not an operator in Python. Consider this session:

>>>"a"in"b","a"(False, 'a')

Since the comma is not an operator, but a separator between expressions theabove is evaluated as if you had entered:

("a"in"b"),"a"

而不是:

"a"in("b","a")

The same is true of the various assignment operators (=,+= etc). Theyare not truly operators but syntactic delimiters in assignment statements.

是否有等效於 C 的 "?:" 三元運算子?

有的,語法如下:

[on_true]if[expression]else[on_false]x,y=50,25small=xifx<yelsey

Before this syntax was introduced in Python 2.5, a common idiom was to uselogical operators:

[expression]and[on_true]or[on_false]

However, this idiom is unsafe, as it can give wrong results whenon_truehas a false boolean value. Therefore, it is always better to usethe...if...else... form.

Is it possible to write obfuscated one-liners in Python?

Yes. Usually this is done by nestinglambda withinlambda. See the following three examples, slightly adapted from Ulf Bartelt:

fromfunctoolsimportreduce# Primes < 1000print(list(filter(None,map(lambday:y*reduce(lambdax,y:x*y!=0,map(lambdax,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))))# First 10 Fibonacci numbersprint(list(map(lambdax,f=lambdax,f:(f(x-1,f)+f(x-2,f))ifx>1else1:f(x,f),range(10))))# Mandelbrot setprint((lambdaRu,Ro,Iu,Io,IM,Sx,Sy:reduce(lambdax,y:x+'\n'+y,map(lambday,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambdayc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,Sx=Sx,Sy=Sy:reduce(lambdax,y:x+y,map(lambdax,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,i=i,Sx=Sx,F=lambdaxc,yc,x,y,k,f=lambdaxc,yc,x,y,k,f:(k<=0)or(x*x+y*y>=4.0)or1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy))))(-2.1,0.7,-1.2,1.2,30,80,24))#    \___ ___/  \___ ___/  |   |   |__ lines on screen#        V          V      |   |______ columns on screen#        |          |      |__________ maximum of "iterations"#        |          |_________________ range on y axis#        |____________________________ range on x axis

孩子們,不要在家裡嘗試這個!

函式參數串列中的斜線 (/) 是什麼意思?

A slash in the argument list of a function denotes that the parameters prior toit are positional-only. Positional-only parameters are the ones without anexternally usable name. Upon calling a function that accepts positional-onlyparameters, arguments are mapped to parameters based solely on their position.For example,divmod() is a function that accepts positional-onlyparameters. Its documentation looks like this:

>>>help(divmod)Help on built-in function divmod in module builtins:divmod(x, y, /)    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.

參數串列最後的斜線表示兩個參數都是僅限位置參數。因此使用關鍵字引數呼叫divmod() 會導致錯誤:

>>>divmod(x=3,y=4)Traceback (most recent call last):  File"<stdin>", line1, in<module>TypeError:divmod() takes no keyword arguments

數字和字串

如何指定十六進位和八進位整數?

To specify an octal digit, precede the octal value with a zero, and then a loweror uppercase "o". For example, to set the variable "a" to the octal value "10"(8 in decimal), type:

>>>a=0o10>>>a8

Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,and then a lower or uppercase "x". Hexadecimal digits can be specified in loweror uppercase. For example, in the Python interpreter:

>>>a=0xa5>>>a165>>>b=0XB2>>>b178

為什麼 -22 // 10 回傳 -3?

It's primarily driven by the desire thati%j have the same sign asj.If you want that, and also want:

i==(i//j)*j+(i%j)

那麼整數除法必須回傳向下取整的結果。 C 還要求保留​​該識別性,然後截斷i//j 的編譯器需要使i%j 具有與i 相同的符號。

There are few real use cases fori%j whenj is negative. Whenjis positive, there are many, and in virtually all of them it's more useful fori%j to be>=0. If the clock says 10 now, what did it say 200 hoursago?-190%12==2 is useful;-190%12==-10 is a bug waiting tobite.

How do I get int literal attribute instead of SyntaxError?

嘗試以正常方式查找int 字面值屬性會給出一個SyntaxError,因為句點被視為小數點:

>>>1.__class__  File"<stdin>", line1  1.__class__   ^SyntaxError:invalid decimal literal

解決方式是用空格或圓括號將字面值與句點分開。

>>>1.__class__<class 'int'>>>>(1).__class__<class 'int'>

如何將字串轉換為數字?

For integers, use the built-inint() type constructor, e.g.int('144')==144. Similarly,float() converts to a floating-point number,e.g.float('144')==144.0.

By default, these interpret the number as decimal, so thatint('0144')==144 holds true, andint('0x144') raisesValueError.int(string,base) takes the base to convert from as a second optional argument, soint('0x144',16)==324. If the base is specified as 0, the number is interpretedusing Python's rules: a leading '0o' indicates octal, and '0x' indicates a hexnumber.

Do not use the built-in functioneval() if all you need is to convertstrings to numbers.eval() will be significantly slower and it presents asecurity risk: someone could pass you a Python expression that might haveunwanted side effects. For example, someone could pass__import__('os').system("rm-rf$HOME") which would erase your homedirectory.

eval() also has the effect of interpreting numbers as Python expressions,so that e.g.eval('09') gives a syntax error because Python does not allowleading '0' in a decimal number (except '0').

如何將數字轉換為字串?

To convert, e.g., the number144 to the string'144', use the built-in typeconstructorstr(). If you want a hexadecimal or octal representation, usethe built-in functionshex() oroct(). For fancy formatting, seethef-string(f 字串) and格式化文字語法 sections,e.g."{:04d}".format(144) yields'0144' and"{:.3f}".format(1.0/3.0) yields'0.333'.

如何原地修改字串?

這沒辦法做到,因為字串是不可變的。在大多數情況下,你應以要拿來組裝的各個部分建構出一個新字串。但是如果你需要一個能夠原地修改 unicode 資料的物件,請嘗試使用io.StringIO 物件或array 模組:

>>>importio>>>s="Hello, world">>>sio=io.StringIO(s)>>>sio.getvalue()'Hello, world'>>>sio.seek(7)7>>>sio.write("there!")6>>>sio.getvalue()'Hello, there!'>>>importarray>>>a=array.array('w',s)>>>print(a)array('w', 'Hello, world')>>>a[0]='y'>>>print(a)array('w', 'yello, world')>>>a.tounicode()'yello, world'

如何使用字串呼叫函式/方法?

有各式各樣的技法。

  • The best is to use a dictionary that maps strings to functions. The primaryadvantage of this technique is that the strings do not need to match the namesof the functions. This is also the primary technique used to emulate a caseconstruct:

    defa():passdefb():passdispatch={'go':a,'stop':b}# Note lack of parens for funcsdispatch[get_input()]()# Note trailing parens to call function
  • 使用內建函式getattr()

    importfoogetattr(foo,'bar')()

    請注意getattr() 適用於任何物件,包括類別、類別實例、模組等。

    這在標準函式庫中的幾個地方被使用,如:

    classFoo:defdo_foo(self):...defdo_bar(self):...f=getattr(foo_instance,'do_'+opname)f()
  • 使用locals() 解析函式名稱:

    defmyFunc():print("hello")fname="myFunc"f=locals()[fname]f()

Is there an equivalent to Perl'schomp() for removing trailing newlines from strings?

You can useS.rstrip("\r\n") to remove all occurrences of any lineterminator from the end of the stringS without removing other trailingwhitespace. If the stringS represents more than one line, with severalempty lines at the end, the line terminators for all the blank lines willbe removed:

>>>lines=("line 1\r\n"..."\r\n"..."\r\n")>>>lines.rstrip("\n\r")'line 1 '

Since this is typically only desired when reading text one line at a time, usingS.rstrip() this way works well.

Is there ascanf() orsscanf() equivalent?

Not as such.

For simple input parsing, the easiest approach is usually to split the line intowhitespace-delimited words using thesplit() method of string objectsand then convert decimal strings to numeric values usingint() orfloat().split() supports an optional "sep" parameter which is usefulif the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions are more powerfulthan C'ssscanf and better suited for the task.

What doesUnicodeDecodeError orUnicodeEncodeError error mean?

請參閱Unicode HOWTO

Can I end a raw string with an odd number of backslashes?

A raw string ending with an odd number of backslashes will escape the string's quote:

>>>r'C:\this\will\not\work\'  File"<stdin>", line1r'C:\this\will\not\work\'^SyntaxError:unterminated string literal (detected at line 1)

There are several workarounds for this. One is to use regular strings and doublethe backslashes:

>>>'C:\\this\\will\\work\\''C:\\this\\will\\work\\'

Another is to concatenate a regular string containing an escaped backslash to theraw string:

>>>r'C:\this\will\work''\\''C:\\this\\will\\work\\'

It is also possible to useos.path.join() to append a backslash on Windows:

>>>os.path.join(r'C:\this\will\work','')'C:\\this\\will\\work\\'

Note that while a backslash will "escape" a quote for the purposes ofdetermining where the raw string ends, no escaping occurs when interpreting thevalue of the raw string. That is, the backslash remains present in the value ofthe raw string:

>>>r'backslash\'preserved'"backslash\\'preserved"

Also see the specification in thelanguage reference.

效能

我的程式太慢了。我該如何加快速度?

That's a tough one, in general. First, here are a list of things toremember before diving further:

  • Performance characteristics vary across Python implementations. This FAQfocuses onCPython.

  • Behaviour can vary across operating systems, especially when talking aboutI/O or multi-threading.

  • You should always find the hot spots in your programbefore attempting tooptimize any code (see theprofile module).

  • Writing benchmark scripts will allow you to iterate quickly when searchingfor improvements (see thetimeit module).

  • It is highly recommended to have good code coverage (through unit testingor any other technique) before potentially introducing regressions hiddenin sophisticated optimizations.

That being said, there are many tricks to speed up Python code. Here aresome general principles which go a long way towards reaching acceptableperformance levels:

  • Making your algorithms faster (or changing to faster ones) can yieldmuch larger benefits than trying to sprinkle micro-optimization tricksall over your code.

  • Use the right data structures. Study documentation for the內建型別and thecollections module.

  • When the standard library provides a primitive for doing something, it islikely (although not guaranteed) to be faster than any alternative youmay come up with. This is doubly true for primitives written in C, suchas builtins and some extension types. For example, be sure to useeither thelist.sort() built-in method or the relatedsorted()function to do sorting (and see the排序技法 for examplesof moderately advanced usage).

  • Abstractions tend to create indirections and force the interpreter to workmore. If the levels of indirection outweigh the amount of useful workdone, your program will be slower. You should avoid excessive abstraction,especially under the form of tiny functions or methods (which are also oftendetrimental to readability).

If you have reached the limit of what pure Python can allow, there are toolsto take you further away. For example,Cython cancompile a slightly modified version of Python code into a C extension, andcan be used on many different platforms. Cython can take advantage ofcompilation (and optional type annotations) to make your code significantlyfaster than when interpreted. If you are confident in your C programmingskills, you can alsowrite a C extension moduleyourself.

也參考

有個 wiki 頁面專門介紹效能改進小提示

What is the most efficient way to concatenate many strings together?

str andbytes objects are immutable, therefore concatenatingmany strings together is inefficient as each concatenation creates a newobject. In the general case, the total runtime cost is quadratic in thetotal string length.

To accumulate manystr objects, the recommended idiom is to placethem into a list and callstr.join() at the end:

chunks=[]forsinmy_strings:chunks.append(s)result=''.join(chunks)

(another reasonably efficient idiom is to useio.StringIO)

To accumulate manybytes objects, the recommended idiom is to extendabytearray object using in-place concatenation (the+= operator):

result=bytearray()forbinmy_bytes_objects:result+=b

序列(元組/串列)

如何在元組和串列之間進行轉換?

型別建構函式tuple(seq) 將任何序列(實際上是任何可疊代物件)轉換為具有相同順序的相同項的元組。

For example,tuple([1,2,3]) yields(1,2,3) andtuple('abc')yields('a','b','c'). If the argument is a tuple, it does not make a copybut returns the same object, so it is cheap to calltuple() when youaren't sure that an object is already a tuple.

The type constructorlist(seq) converts any sequence or iterable into a listwith the same items in the same order. For example,list((1,2,3)) yields[1,2,3] andlist('abc') yields['a','b','c']. If the argumentis a list, it makes a copy just likeseq[:] would.

什麼是負索引?

Python sequences are indexed with positive numbers and negative numbers. Forpositive numbers 0 is the first index 1 is the second index and so forth. Fornegative indices -1 is the last index and -2 is the penultimate (next to last)index and so forth. Think ofseq[-n] as the same asseq[len(seq)-n].

Using negative indices can be very convenient. For exampleS[:-1] is all ofthe string except for its last character, which is useful for removing thetrailing newline from a string.

How do I iterate over a sequence in reverse order?

Use thereversed() built-in function:

forxinreversed(sequence):...# do something with x ...

This won't touch your original sequence, but build a new copy with reversedorder to iterate over.

如何從串列中刪除重複項?

請參閱 Python Cookbook 以得到有關執行此操作的各種方法的詳細討論:

如果你不介意重新排序串列,可以對其進行排序,然後從串列末尾開始掃描,同時刪除重複項:

ifmylist:mylist.sort()last=mylist[-1]foriinrange(len(mylist)-2,-1,-1):iflast==mylist[i]:delmylist[i]else:last=mylist[i]

如果串列的所有元素都可以做為集合的鍵(即它們都必須是hashable),那這通常會更快:

mylist=list(set(mylist))

這會將串列轉換為一個集合,從而刪除重複項,然後再轉換回串列。

如何從串列中刪除多個項目

As with removing duplicates, explicitly iterating in reverse with adelete condition is one possibility. However, it is easier and fasterto use slice replacement with an implicit or explicit forward iteration.Here are three variations.:

mylist[:]=filter(keep_function,mylist)mylist[:]=(xforxinmylistifkeep_condition)mylist[:]=[xforxinmylistifkeep_condition]

The list comprehension may be fastest.

How do you make an array in Python?

Use a list:

["this",1,"is","an","array"]

Lists are equivalent to C or Pascal arrays in their time complexity; the primarydifference is that a Python list can contain objects of many different types.

Thearray module also provides methods for creating arrays of fixed typeswith compact representations, but they are slower to index than lists. Alsonote thatNumPyand other third party packages define array-like structures withvarious characteristics as well.

To get Lisp-style linked lists, you can emulatecons cells using tuples:

lisp_list=("like",("this",("example",None)))

If mutability is desired, you could use lists instead of tuples. Here theanalogue of a Lispcar islisp_list[0] and the analogue ofcdr islisp_list[1]. Only do this if you're sure you really need to, because it'susually a lot slower than using Python lists.

如何建立多維度串列?

你可能會這樣建立一個多維度陣列:

>>>A=[[None]*2]*3

如果你印出它,這看起來是正確的:

>>>A[[None, None], [None, None], [None, None]]

但是當你賦予一個值時,它會出現在多個地方:

>>>A[0][0]=5>>>A[[5, None], [5, None], [5, None]]

原因是複製帶有* 的串列不會建立副本,它只會建立對現有物件的參照。*3 建立一個串列,其中包含 3 個對長度為 2 的相同串列的參照。對其中一列的變更也將顯示在所有其他列中,而這幾乎不會是你想要的。

建議的方法是先建立所需長度的串列,然後用新建立的串列填充每個元素:

A=[None]*3foriinrange(3):A[i]=[None]*2

這會產生一個包含 3 個長度為 2 的不同串列的串列。你也可以使用串列綜合運算式:

w,h=2,3A=[[None]*wforiinrange(h)]

或者你也可以使用提供矩陣資料型別的擴充套件;NumPy 是其中最著名的一個。

如何將方法或函式應用於物件序列?

To call a method or function and accumulate the return values is a list,alist comprehension is an elegant solution:

result=[obj.method()forobjinmylist]result=[function(obj)forobjinmylist]

To just run the method or function without saving the return values,a plainfor loop will suffice:

forobjinmylist:obj.method()forobjinmylist:function(obj)

為什麼 a_tuple[i] += ['item'] 做加法時會引發例外?

This is because of a combination of the fact that augmented assignmentoperators areassignment operators, and the difference between mutable andimmutable objects in Python.

This discussion applies in general when augmented assignment operators areapplied to elements of a tuple that point to mutable objects, but we'll usealist and+= as our exemplar.

如果你寫了:

>>>a_tuple=(1,2)>>>a_tuple[0]+=1Traceback (most recent call last):...TypeError:'tuple' object does not support item assignment

The reason for the exception should be immediately clear:1 is added to theobjecta_tuple[0] points to (1), producing the result object,2,but when we attempt to assign the result of the computation,2, to element0 of the tuple, we get an error because we can't change what an element ofa tuple points to.

這個增強賦值陳述式在背後大致是做這些事情:

>>>result=a_tuple[0]+1>>>a_tuple[0]=resultTraceback (most recent call last):...TypeError:'tuple' object does not support item assignment

It is the assignment part of the operation that produces the error, since atuple is immutable.

When you write something like:

>>>a_tuple=(['foo'],'bar')>>>a_tuple[0]+=['item']Traceback (most recent call last):...TypeError:'tuple' object does not support item assignment

The exception is a bit more surprising, and even more surprising is the factthat even though there was an error, the append worked:

>>>a_tuple[0]['foo', 'item']

To see why this happens, you need to know that (a) if an object implements an__iadd__() magic method, it gets called when the+= augmentedassignmentis executed, and its return value is what gets used in the assignment statement;and (b) for lists,__iadd__() is equivalent to callingextend() on the listand returning the list. That's why we say that for lists,+= is a"shorthand" forlist.extend():

>>>a_list=[]>>>a_list+=[1]>>>a_list[1]

這等價於:

>>>result=a_list.__iadd__([1])>>>a_list=result

The object pointed to by a_list has been mutated, and the pointer to themutated object is assigned back toa_list. The end result of theassignment is a no-op, since it is a pointer to the same object thata_listwas previously pointing to, but the assignment still happens.

因此,在我們的元組範例中,發生的事情等同於:

>>>result=a_tuple[0].__iadd__(['item'])>>>a_tuple[0]=resultTraceback (most recent call last):...TypeError:'tuple' object does not support item assignment

The__iadd__() succeeds, and thus the list is extended, but even thoughresult points to the same object thata_tuple[0] already points to,that final assignment still results in an error, because tuples are immutable.

我想做一個複雜的排序:你能用 Python 做一個 Schwartzian 變換嗎?

The technique, attributed to Randal Schwartz of the Perl community, sorts theelements of a list by a metric which maps each element to its "sort value". InPython, use thekey argument for thelist.sort() method:

Isorted=L[:]Isorted.sort(key=lambdas:int(s[10:15]))

如何根據另一個串列中的值對一個串列進行排序?

將它們合併到一個元組疊代器中,對結果的串列進行排序,然後挑選出你想要的元素。

>>>list1=["what","I'm","sorting","by"]>>>list2=["something","else","to","sort"]>>>pairs=zip(list1,list2)>>>pairs=sorted(pairs)>>>pairs[("I'm", 'else'), ('by', 'sort'), ('sorting', 'to'), ('what', 'something')]>>>result=[x[1]forxinpairs]>>>result['else', 'sort', 'to', 'something']

物件

什麼是類別 (class)?

A class is the particular object type created by executing a class statement.Class objects are used as templates to create instance objects, which embodyboth the data (attributes) and code (methods) specific to a datatype.

A class can be based on one or more other classes, called its base class(es). Itthen inherits the attributes and methods of its base classes. This allows anobject model to be successively refined by inheritance. You might have agenericMailbox class that provides basic accessor methods for a mailbox,and subclasses such asMboxMailbox,MaildirMailbox,OutlookMailboxthat handle various specific mailbox formats.

什麼是方法 (method)?

A method is a function on some objectx that you normally call asx.name(arguments...). Methods are defined as functions inside the classdefinition:

classC:defmeth(self,arg):returnarg*2+self.attribute

什麼是 self?

Self 只是方法第一個引數的約定名稱。對於所定義類別的某個實例x,一個定義為meth(self,a,b,c) 的方法應該以x.meth(a,b,c) 形式來呼叫;被呼叫的方法會認為它是以meth(x,a,b,c) 來呼叫的。

另請參閱為何「self」在方法 (method) 定義和呼叫時一定要明確使用?

如何檢查物件是否是給定類別的實例或其子類別的實例?

Use the built-in functionisinstance(obj,cls). You cancheck if an objectis an instance of any of a number of classes by providing a tuple instead of asingle class, e.g.isinstance(obj,(class1,class2,...)), and can alsocheck whether an object is one of Python's built-in types, e.g.isinstance(obj,str) orisinstance(obj,(int,float,complex)).

請注意,isinstance() 還會檢查來自抽象基底類別 (abstract base class) 的虛擬繼承。因此對已註冊類別的檢驗會回傳True,即使沒有直接或間接繼承自它。要測試「真正繼承」,請掃描該類別的MRO

fromcollections.abcimportMappingclassP:passclassC(P):passMapping.register(P)
>>>c=C()>>>isinstance(c,C)# 直接True>>>isinstance(c,P)# 間接True>>>isinstance(c,Mapping)# 虛擬True# 實際的繼承鏈結>>>type(c).__mro__(<class 'C'>, <class 'P'>, <class 'object'>)# 「真正繼承」的檢驗>>>Mappingintype(c).__mro__False

Note that most programs do not useisinstance() on user-defined classesvery often. If you are developing the classes yourself, a more properobject-oriented style is to define methods on the classes that encapsulate aparticular behaviour, instead of checking the object's class and doing adifferent thing based on what class it is. For example, if you have a functionthat does something:

defsearch(obj):ifisinstance(obj,Mailbox):...# 搜尋信箱的程式碼elifisinstance(obj,Document):...# 搜尋文件的程式碼elif...

更好的方法是在所有類別上定義一個search() 方法然後呼叫它:

classMailbox:defsearch(self):...# 搜尋信箱的程式碼classDocument:defsearch(self):...# 搜尋文件的程式碼obj.search()

什麼是委派 (delegation)?

委派是一種物件導向的技法(也稱為設計模式)。假設你有一個物件x 並且只想更改其中一個方法的行為。你可以建立一個新類別,它提供你想改變的那個方法的新實作,並將所有其他方法委派給x 的相應方法。

Python 程式設計師可以輕鬆地實作委派。舉例來說,以下類別實作了一個行為類似檔案的類別,但將所有寫入的資料轉換為大寫:

classUpperOut:def__init__(self,outfile):self._outfile=outfiledefwrite(self,s):self._outfile.write(s.upper())def__getattr__(self,name):returngetattr(self._outfile,name)

Here theUpperOut class redefines thewrite() method to convert theargument string to uppercase before calling the underlyingself._outfile.write() method. All other methods are delegated to theunderlyingself._outfile object. The delegation is accomplished via the__getattr__() method; consultthe language referencefor more information about controlling attribute access.

Note that for more general cases delegation can get trickier. When attributesmust be set as well as retrieved, the class must define a__setattr__()method too, and it must do so carefully. The basic implementation of__setattr__() is roughly equivalent to the following:

classX:...def__setattr__(self,name,value):self.__dict__[name]=value...

許多__setattr__() 的實作會呼叫object.__setattr__() 以設定 self 的屬性,而不會導致無限遞迴。

classX:def__setattr__(self,name,value):# 自訂邏輯放在這裡...object.__setattr__(self,name,value)

Alternatively, it is possible to set attributes by insertingentries intoself.__dict__ directly.

How do I call a method defined in a base class from a derived class that extends it?

使用內建的super() 函式:

classDerived(Base):defmeth(self):super().meth()# 呼叫 Base.meth

In the example,super() will automatically determine the instance fromwhich it was called (theself value), look up themethod resolutionorder (MRO) withtype(self).__mro__, and return the next in line afterDerived in the MRO:Base.

我可以如何組織我的程式碼以使得更改基底類別變的更容易?

You could assign the base class to an alias and derive from the alias. Then allyou have to change is the value assigned to the alias. Incidentally, this trickis also handy if you want to decide dynamically (e.g. depending on availabilityof resources) which base class to use. Example:

classBase:...BaseAlias=BaseclassDerived(BaseAlias):...

如何建立靜態類別資料和靜態類別方法?

Python 支援靜態資料和靜態方法(在 C++ 或 Java 的意義上)。

對於靜態資料,只需定義一個類別屬性即可。要為屬性分配新值,你必須在分配中顯式使用類別名稱:

classC:count=0# C.__init__ 被呼叫的次數def__init__(self):C.count=C.count+1defgetcount(self):returnC.count# 或回傳 self.count

c.count 還指代任何cC.count 使得isinstance(c,C) 成立,除非被c 本身或某些人覆蓋從c.__class__ 回到C 的基底類別搜尋路徑上的類別。

Caution: within a method of C, an assignment likeself.count=42 creates anew and unrelated instance named "count" inself's own dict. Rebinding of aclass-static data name must always specify the class whether inside a method ornot:

C.count=314

靜態方法是可能的:

classC:@staticmethoddefstatic(arg1,arg2,arg3):# 沒有 'self' 參數!...

However, a far more straightforward way to get the effect of a static method isvia a simple module-level function:

defgetcount():returnC.count

If your code is structured so as to define one class (or tightly related classhierarchy) per module, this supplies the desired encapsulation.

如何在 Python 中多載 (overload) 建構函式(或方法)?

這個答案實際上適用於所有方法,但這個問題通常會先出現在建構函式的情境中。

在 C++ 中你會寫成

classC{C(){cout<<"No arguments\n";}C(inti){cout<<"Argument is "<<i<<"\n";}}

在 Python 中,你必須編寫一個建構函式來捕獲所有使用預設引數的情況。例如:

classC:def__init__(self,i=None):ifiisNone:print("No arguments")else:print("Argument is",i)

這並不完全等價,但在實際情況中已夠接近。

你也可以嘗試長度可變的引數串列,例如:

def__init__(self,*args):...

相同的手段適用於所有方法的定義。

我嘗試使用 __spam,但收到有關 _SomeClassName__spam 的錯誤。

帶有雙前導底線的變數名會被「破壞 (mangled)」以做為提供定義類別私有變數的一個簡單但有效的方法。__spam 形式的任何識別字(至少兩個前導底線,最多一個尾隨底線)在文字上會被替換為_classname__spam,其中classname 是目前類別之所有前導底線被去除的名稱。

The identifier can be used unchanged within the class, but to access it outsidethe class, the mangled name must be used:

classA:def__one(self):return1deftwo(self):return2*self.__one()classB(A):defthree(self):return3*self._A__one()four=4*A()._A__one()

In particular, this does not guarantee privacy since an outside user can stilldeliberately access the private attribute; many Python programmers never botherto use private variable names at all.

也參考

Theprivate name mangling specificationsfor details and special cases.

我的類別定義了 __del__ 但是當我刪除物件時它沒有被呼叫。

這有幾個可能的原因。

del 陳述式不一定會呼叫__del__() -- 它只是減少物件的參照計數,如果達到零則呼叫__del__()

If your data structures contain circular links (e.g. a tree where each child hasa parent reference and each parent has a list of children) the reference countswill never go back to zero. Once in a while Python runs an algorithm to detectsuch cycles, but the garbage collector might run some time after the lastreference to your data structure vanishes, so your__del__() method may becalled at an inconvenient and random time. This is inconvenient if you're tryingto reproduce a problem. Worse, the order in which object's__del__()methods are executed is arbitrary. You can rungc.collect() to force acollection, but thereare pathological cases where objects will never becollected.

Despite the cycle collector, it's still a good idea to define an explicitclose() method on objects to be called whenever you're done with them. Theclose() method can then remove attributes that refer to subobjects. Don'tcall__del__() directly --__del__() should callclose() andclose() should make sure that it can be called more than once for the sameobject.

Another way to avoid cyclical references is to use theweakref module,which allows you to point to objects without incrementing their reference count.Tree data structures, for instance, should use weak references for their parentand sibling references (if they need them!).

最後,如果你的__del__() 方法引發例外,則會將一條警告訊息印出到sys.stderr

我該如何取得給定類別的所有實例的串列?

Python 不會追蹤類別(或內建型別)的所有實例。你可以將類別的建構函式進行改寫,以透過保留對每個實例之弱參照串列來追蹤所有實例。

為什麼id() 的結果看起來不唯一?

Theid() builtin returns an integer that is guaranteed to be unique duringthe lifetime of the object. Since in CPython, this is the object's memoryaddress, it happens frequently that after an object is deleted from memory, thenext freshly created object is allocated at the same position in memory. Thisis illustrated by this example:

>>>id(1000)13901272>>>id(2000)13901272

The two ids belong to different integer objects that are created before, anddeleted immediately after execution of theid() call. To be sure thatobjects whose id you want to examine are still alive, create another referenceto the object:

>>>a=1000;b=2000>>>id(a)13901272>>>id(b)13891296

我什麼時候可以依靠is 運算子進行識別性測試?

is 運算子測試物件識別性。測試aisb 等同於id(a)==id(b)

識別性測試最重要的屬性是物件始終與自身相同,aisa 總是回傳True 。識別性測試通常比相等性測試更快。與相等性測試不同,識別性測試保證回傳布林值TrueFalse

然而,只有當物件識別性得到保證時,識別性測試才能代替相等性測試。一般來說,保證識別性的情況有以下三種:

  1. Assignments create new names but do not change object identity. After theassignmentnew=old, it is guaranteed thatnewisold.

  2. Putting an object in a container that stores object references does notchange object identity. After the list assignments[0]=x, it isguaranteed thats[0]isx.

  3. If an object is a singleton, it means that only one instance of that objectcan exist. After the assignmentsa=None andb=None, it isguaranteed thataisb becauseNone is a singleton.

在大多數其他情況下,識別性測試是不可取的,相等性測試是首選。特別是,識別性測試不應用於檢查常數,例如不能保證是單例的intstr

>>>a=1000>>>b=500>>>c=b+500>>>aiscFalse>>>a='Python'>>>b='Py'>>>c=b+'thon'>>>aiscFalse

同樣地,可變容器的新實例永遠不會相同:

>>>a=[]>>>b=[]>>>aisbFalse

在標準函式庫程式碼中,你將看到幾種正確使用識別性測試的常見模式:

  1. 正如PEP 8 所推薦的,識別性測試是檢查None 的首選方法。這在程式碼中讀起來像簡單的英語,並避免與其他可能具有評估為 false 的布林值的物件混淆。

  2. Detecting optional arguments can be tricky whenNone is a valid inputvalue. In those situations, you can create a singleton sentinel objectguaranteed to be distinct from other objects. For example, here is howto implement a method that behaves likedict.pop():

    _sentinel=object()defpop(self,key,default=_sentinel):ifkeyinself:value=self[key]delself[key]returnvalueifdefaultis_sentinel:raiseKeyError(key)returndefault
  3. 容器實作有時需要透過識別性測試來增強相等性測試。這可以防止程式碼被諸如 float('NaN') 之類的不等於自身的物件所混淆。

例如,以下是collections.abc.Sequence.__contains__() 的實作:

def__contains__(self,value):forvinself:ifvisvalueorv==value:returnTruereturnFalse

子類別如何控制不可變實例中存儲的資料?

When subclassing an immutable type, override the__new__() methodinstead of the__init__() method. The latter only runsafter aninstance is created, which is too late to alter data in an immutableinstance.

所有這些不可變類別都具有與其父類別不同的簽名:

fromdatetimeimportdateclassFirstOfMonthDate(date):"總是選擇每個月的第一天"def__new__(cls,year,month,day):returnsuper().__new__(cls,year,month,1)classNamedInt(int):"允許一些數字的文字名稱"xlat={'zero':0,'one':1,'ten':10}def__new__(cls,value):value=cls.xlat.get(value,value)returnsuper().__new__(cls,value)classTitleStr(str):"將 str 轉換成適合作為 URL 路徑的名稱"def__new__(cls,s):s=s.lower().replace(' ','-')s=''.join([cforcinsifc.isalnum()orc=='-'])returnsuper().__new__(cls,s)

這些類別可以像這樣使用:

>>>FirstOfMonthDate(2012,2,14)FirstOfMonthDate(2012, 2, 1)>>>NamedInt('ten')10>>>NamedInt(20)20>>>TitleStr('Blog: Why Python Rocks')'blog-why-python-rocks'

如何快取方法呼叫?

The two principal tools for caching methods arefunctools.cached_property() andfunctools.lru_cache(). Theformer stores results at the instance level and the latter at the classlevel.

Thecached_property approach only works with methods that do not takeany arguments. It does not create a reference to the instance. Thecached method result will be kept only as long as the instance is alive.

The advantage is that when an instance is no longer used, the cachedmethod result will be released right away. The disadvantage is that ifinstances accumulate, so too will the accumulated method results. Theycan grow without bound.

lru_cache 方法適用於具有可雜湊引數的方法。除非特別努力傳遞弱參照,否則它會建立對實例的參照。

The advantage of the least recently used algorithm is that the cache isbounded by the specifiedmaxsize. The disadvantage is that instancesare kept alive until they age out of the cache or until the cache iscleared.

這個例子展示了各種技術:

classWeather:"Lookup weather information on a government website"def__init__(self,station_id):self._station_id=station_id# The _station_id is private and immutabledefcurrent_temperature(self):"Latest hourly observation"# Do not cache this because old results# can be out of date.@cached_propertydeflocation(self):"Return the longitude/latitude coordinates of the station"# Result only depends on the station_id@lru_cache(maxsize=20)defhistoric_rainfall(self,date,units='mm'):"Rainfall on a given date"# Depends on the station_id, date, and units.

The above example assumes that thestation_id never changes. If therelevant instance attributes are mutable, thecached_property approachcan't be made to work because it cannot detect changes to theattributes.

To make thelru_cache approach work when thestation_id is mutable,the class needs to define the__eq__() and__hash__()methods so that the cache can detect relevant attribute updates:

classWeather:"Example with a mutable station identifier"def__init__(self,station_id):self.station_id=station_iddefchange_station(self,station_id):self.station_id=station_iddef__eq__(self,other):returnself.station_id==other.station_iddef__hash__(self):returnhash(self.station_id)@lru_cache(maxsize=20)defhistoric_rainfall(self,date,units='cm'):'Rainfall on a given date'# Depends on the station_id, date, and units.

模組

如何建立 .pyc 檔案?

When a module is imported for the first time (or when the source file haschanged since the current compiled file was created) a.pyc file containingthe compiled code should be created in a__pycache__ subdirectory of thedirectory containing the.py file. The.pyc file will have afilename that starts with the same name as the.py file, and ends with.pyc, with a middle component that depends on the particularpythonbinary that created it. (SeePEP 3147 for details.)

One reason that a.pyc file may not be created is a permissions problemwith the directory containing the source file, meaning that the__pycache__subdirectory cannot be created. This can happen, for example, if you develop asone user but run as another, such as if you are testing with a web server.

Unless thePYTHONDONTWRITEBYTECODE environment variable is set,creation of a .pyc file is automatic if you're importing a module and Pythonhas the ability (permissions, free space, etc...) to create a__pycache__subdirectory and write the compiled module to that subdirectory.

Running Python on a top level script is not considered an import and no.pyc will be created. For example, if you have a top-level modulefoo.py that imports another modulexyz.py, when you runfoo (bytypingpythonfoo.py as a shell command), a.pyc will be created forxyz becausexyz is imported, but no.pyc file will be created forfoo sincefoo.py isn't being imported.

如果你需要為foo 建立一個.pyc 檔案 —— 也就是說,要為一個未引入的模組建立一個.pyc 檔案 —— 你可以使用py_compilecompileall 模組。

py_compile 模組允許手動編譯任何模組。其中一種方法是在該模組中以交互方式使用compile() 函式:

>>>importpy_compile>>>py_compile.compile('foo.py')

這會將.pyc 寫入與foo.py 相同位置的__pycache__ 子目錄(或者你可以使用可選參數cfile 覆蓋它)。

You can also automatically compile all files in a directory or directories usingthecompileall module. You can do it from the shell prompt by runningcompileall.py and providing the path of a directory containing Python filesto compile:

python-mcompileall.

如何找到目前模組名稱?

A module can find out its own module name by looking at the predefined globalvariable__name__. If this has the value'__main__', the program isrunning as a script. Many modules that are usually used by importing them alsoprovide a command-line interface or a self-test, and only execute this codeafter checking__name__:

defmain():print('Running test...')...if__name__=='__main__':main()

要怎樣才能擁有相互引入的模組?

假設你有以下模組:

foo.py

frombarimportbar_varfoo_var=1

bar.py

fromfooimportfoo_varbar_var=2

問題是直譯器將執行以下步驟:

  • 主要引入foo

  • 建立了foo 的空全域變數

  • foo 被編譯並開始執行

  • foo 引入bar

  • 建立了bar 的空全域變數

  • bar 已被編譯並開始執行

  • bar 引入foo(這是一個空操作,因為已經有一個名為foo 的模組)

  • 引入機制嘗試從foo 全域變數中讀取foo_var,以設定bar.foo_var=foo.foo_var

最後一步失敗了,因為 Python 還沒有完成對foo 的直譯,而foo 的全域符號字典仍然是空的。

The same thing happens when you useimportfoo, and then try to accessfoo.foo_var in global code.

此問題有(至少)三種可能的解決方法。

Guido van Rossum recommends avoiding all uses offrom<module>import...,and placing all code inside functions. Initializations of global variables andclass variables should use constants or built-in functions only. This meanseverything from an imported module is referenced as<module>.<name>.

Jim Roskind 建議在每個模組中按以下順序執行各個步驟:

  • exports (globals, functions, and classes that don't need imported baseclasses)

  • import 陳述式

  • 活躍程式碼(包括從引入值初始化的全域變數)。

Van Rossum 不太喜歡這種方法,因為引入出現在一個奇怪的地方,但它確實有效。

Matthias Urlichs 建議重組 (restructuring) 你的程式碼,以便打從一開始就不需要遞迴引入。

這些方案並不衝突。

__import__('x.y.z') 回傳 <module 'x'>,那我怎麼得到 z?

Consider using the convenience functionimport_module() fromimportlib instead:

z=importlib.import_module('x.y.z')

當我編輯需要引入的模組並重新引入它時,更動沒有反應出來。為什麼會這樣?

For reasons of efficiency as well as consistency, Python only reads the modulefile on the first time a module is imported. If it didn't, in a programconsisting of many modules where each one imports the same basic module, thebasic module would be parsed and re-parsed many times. To force re-reading of achanged module, do this:

importimportlibimportmodnameimportlib.reload(modname)

警告:此技術並非 100% 萬無一失。尤其是包含像這樣陳述式的模組:

frommodnameimportsome_objects

will continue to work with the old version of the imported objects. If themodule contains class definitions, existing class instances willnot beupdated to use the new class definition. This can result in the followingparadoxical behaviour:

>>>importimportlib>>>importcls>>>c=cls.C()# 建立一個 C 的實例>>>importlib.reload(cls)<module 'cls' from 'cls.py'>>>>isinstance(c,cls.C)# isinstance 為 false?!?False

如果印出類別物件的「識別性」,問題的本質就很清楚了:

>>>hex(id(c.__class__))'0x7352a0'>>>hex(id(cls.C))'0x4198d0'