python中那些不为人知的功能特性

常常逛GitHub的可能关注一个牛叉的项目,叫 What the f*ck Python!python

这个项目列出了几乎全部python中那些不为人知的功能特性,有些功能第一次碰见时,你会冒出 what the f**k 的感叹。git

由于这些例子看起来反人类直觉。github

可是若是你理解了它背后的真正原理,你又会惊叹what the f**k, 居然还有这么骚的操做。web

来看看几个例子吧。app

微妙的字符串

>>> a = "wtf"
>>> b = "wtf"
>>> a is b
True

>>> a = "wtf!"
>>> b = "wtf!"
>>> a is b
False

>>> a, b = "wtf!", "wtf!"
>>> a is b 
True # 3.7 版本返回结果为 False.
复制代码

出乎意料的"is"

>>> a = 256
>>> b = 256
>>> a is b
True

>>> a = 257
>>> b = 257
>>> a is b
False

>>> a = 257; b = 257
>>> a is b
True
复制代码

说好的元组不可变呢

some_tuple = ("A", "tuple", "with", "values")
another_tuple = ([1, 2], [3, 4], [5, 6])


>>> some_tuple[2] = "change this"
TypeError: 'tuple' object does not support item assignment
>>> another_tuple[2].append(1000) # 这里不出现错误
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000])
>>> another_tuple[2] += [99, 999]
TypeError: 'tuple' object does not support item assignment
>>> another_tuple
([1, 2], [3, 4], [5, 6, 1000, 99, 999])
复制代码

消失的全局变量

e = 7
try:
    raise Exception()
except Exception as e:
    pass
复制代码

输出this

>>> print(e)
NameError: name 'e' is not defined
复制代码

到底返回哪一个值

def some_func():
    try:
        return 'from_try'
    finally:
        return 'from_finally'
复制代码

输出spa

>>> some_func()
'from_finally'
复制代码

诸如此类的例子一共有50多个code

若是你能把这50多个特性背后的原理机制所有了解清楚,我相信你的python功力必定会上升一个层次。orm

传送门: github.com/leisurelich…cdn

文章首发公众号:python之禅,欢迎关注

https://user-gold-cdn.xitu.io/2017/7/16/4a84df1d3a79ea6aa60d4068ea549f6d?imageView2/0/w/1280/h/960/format/webp/ignore-error/1
相关文章
相关标签/搜索