More Control Flow Tools,Python Tutorial阅读笔记(1)
参考资料:
注:由于感觉自己的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'
可以看到,当我们想使用注释的时候,可以用冒号标识数据类型,箭头标识返回值。