More Control Flow Tools,Python Tutorial閱讀筆記(1)
阿新 • • 發佈:2020-11-18
參考資料:
注:由於感覺自己的Python還沒有學通透,在看專案的程式碼時還是有一些困難。所以想看一下Python官網的Tutorial自學一下,我在讀的時候也是略過了自己已經會的地方,所以我寫的東西都是自己學到的新東西。
規範:黑體x)表示自己學到的東西模組,是一個大概的區分。4.1,4.2表示在Tutorial中的位置。
1)函式的引數中,關鍵詞引數(keyword arguments)一定要在位置引數(positional arguments)後面。
2)4.7.2 函式的定義中,*arguments表示解析一個元組,**arguments表示解析一個字典。注意,元組就好似位置引數,字典就好似關鍵詞引數。例子如下:
def cheeseshop(kind, *arguments, **keywords): print("-- Do you have any", kind, "?") print("-- I'm sorry, we're all out of", kind) for arg in arguments: print(arg) print("-" * 40) for kw in keywords: print(kw, ":", keywords[kw])
我們可以這樣呼叫:
cheeseshop("Limburger", "It's very runny, sir.", "It's really very, VERY runny, sir.", shopkeeper="Michael Palin", client="John Cleese", sketch="Cheese Shop Sketch")
輸出如下:
-- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- shopkeeper : Michael Palin client : John Cleese sketch : Cheese Shop Sketch
3)4.7.3 函式定義中的特殊的引數
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): ----------- ---------- ---------- | | | | Positional or keyword | | - Keyword only -- Positional only
這種方式等於說顯式的在函式定義的時候規定了引數傳遞的方法!比如,如果你的定義是def kwd_only_arg(*, arg): 那麼所有的引數都應該用關鍵詞形式來傳遞!
4)4.7.7函式的文件規範
>>> def my_function(): ... """Do nothing, but document it. ... ... No, really, it doesn't do anything. ... """ ... pass ... >>> print(my_function.__doc__) Do nothing, but document it. No, really, it doesn't do anything.
4.7.8函式的註釋規範:
>>> def f(ham: str, eggs: str = 'eggs') -> str: ... print("Annotations:", f.__annotations__) ... print("Arguments:", ham, eggs) ... return ham + ' and ' + eggs ... >>> f('spam') Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>} Arguments: spam eggs 'spam and eggs'
可以看到,當我們想使用註釋的時候,可以用冒號標識資料型別,箭頭標識返回值。