zoukankan      html  css  js  c++  java
  • python中那些鲜为人知的功能特性

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

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

    因为这些例子看起来反人类直觉。

    很多人学习python,不知道从何学起。
    很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
    很多已经做案例的人,却不知道如何去学习更加高深的知识。
    那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
    QQ群:1097524789

    但是如果你理解了它背后的真正原理,你又会惊叹what the f**k, 竟然还有这么骚的操作。

    来看看几个例子吧。

    微妙的字符串

    >>> 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
    复制代码

    输出

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

    到底返回哪个值

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

    输出

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

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

    如果你能把这50多个特性背后的原理机制全部了解清楚,我相信你的python功力一定会上升一个层次。

    https://github.com/leisurelicht/wtfpython-cn

  • 相关阅读:
    接口和实现接口的类
    类的封装
    实验六:类的封装
    实验五:任意输入10个int类型数据,排序输出,再找出素数
    实验四:采用一维数组输出等腰三角形的杨辉三角
    2017-12-31 小组工作记录
    2017-12-30 小组工作记录
    2017-12-29 小组工作记录
    2017-12-24 小组工作记录
    2017-12-21 小组工作记录
  • 原文地址:https://www.cnblogs.com/shann001/p/13162694.html
Copyright © 2011-2022 走看看