LOADING STUFF...

Python黑魔法手册 2.0 文档第一章【17-20】

Python2年前 (2022)发布 safedragon
87 0

Python黑魔法手册

第一章:魔法冷知识【17-20】

1.17 有趣但没啥用的 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黑魔法手册 2.0 文档第一章【17-20】

1.18 正负得正,负负得正

从初中开始,我们就开始接触了 负数 ,并且都知道了 负负得正 的思想。
Python 作为一门高级语言,它的编写符合人类的思维逻辑,包括 负负得正

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

1.19 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 仍然有效。

1.20 字符串里的缝隙是什么?

在Python中求一个字符串里,某子字符(串)出现的次数。

大家都懂得使用 count() 函数,比如下面几个常规例子:

>>> "aabb".count("a")
2
>>> "aabb".count("b")
2
>>> "aabb".count("ab")
1

但是如果我想计算空字符串的个数呢?

>>> "aabb".count("")
5

奇怪了吧?

不是应该返回 0 吗?怎么会返回 5?

实际上,在 Python 看来,两个字符之间都是一个空字符,通俗的说就是缝隙。

因此 对于 aabb 这个字符串在 Python 来看应该是这样的

Python黑魔法手册 2.0 文档第一章【17-20】

理解了这个“缝隙” 的概念后,以下这些就好理解了。

>>> (" " * 10).count("")
11
>>>
>>> "" in ""
True
>>>
>>> "" in "M"
True

 

© 版权声明

相关文章

暂无评论

暂无评论...