python基础知识点(五)

描述

有趣但没啥用的 import 用法

import 是 Python 导包的方式。

你知道 Python 中内置了一些很有(wu)趣(liao)的包吗?

Hello World

>>> import __hello__
Hello World!

Python之禅

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

反地心引力漫画

在 cmd 窗口中导入antigravity

>>> import antigravity

就会自动打开一个网页。

正负得负,负负得正

从初中开始,我们就开始接触了负数 ,并且都知道了负负得正 的思想。

Python 作为一门高级语言,它的编写符合人类的思维逻辑,包括 负负得正

>>> 5-3
2
>>> 5--3
8
>>> 5+-3
2
>>> 5++3
8
>>> 5---3
2

return不一定都是函数的终点

众所周知,try…finally… 的用法是:不管try里面是正常执行还是有报异常,最终都能保证finally能够执行。

同时我们又知道,一个函数里只要遇到 return 函数就会立马结束。

那问题就来了,以上这两种规则,如果同时存在,Python 解释器会如何选择?哪个优先级更高?

写个示例验证一下,就明白啦

>>> def func():
...     try:
...         return 'try'
...     finally:
...         return 'finally'
...
>>> func()
'finally'

从输出中,我们可以发现:在try…finally…语句中,try中的 return 会被直接忽视(这里的 return 不是函数的终点),因为要保证 finally 能够执行。

如果 try 里的 return 真的是直接被忽视吗?

我们都知道如果一个函数没有 return,会隐式的返回 None,假设 try 里的 return 真的是直接被忽视,那当finally 下没有显式的 return 的时候,是不是会返回None呢?

还是写个 示例来验证一下:

>>> def func():
...     try:
...         return 'try'
...     finally:
...         print('finally')
...
>>>
>>> func()
finally
'try'

从结果来看,当 finally 下没有 reutrn ,其实 try 里的 return 仍然还是有效的。

那结论就出来了,如果 finally 里有显式的 return,那么这个 return 会直接覆盖 try 里的 return,而如果 finally 里没有 显式的 return,那么 try 里的 return 仍然有效。
审核编辑:汤梓红

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分