Python高级特性(一)

is 和 ==

  • Python中对象包含的三个基本要素闭包

    • id 身份标识
    • type 数据类型
    • value 值
  • is判断对象的ID是否相同,==判断对象的value是否相同app

    def test_num():
        n1 = 1
        n2 = 1
        print(n1 == n2, id(n1))
        print(n1 is n2, id(n2))
    
        # result:
            #True 1927373024
            #True 1927373024
        
    
    def test_str():
        s1 = "hello"
        s2 = "hello"
        print(s1 == s2, id(s1))
        print(s1 is s2, id(s2))
    
        # result:
            # True 2085262242568
            # True 2085262242568
    
    
    def test_li():
        li1 = [1, 2]
        li2 = [1, 2]
        print(li1 == li2, id(li1))
        print(li1 is li2, id(li2))
    
        # result:
            # True 2481770446536
            # False 2481770446472
  • 结论:数字和字符串value相同时时,is为True,不然为False函数

对象拷贝

不可变对象:一旦建立就不可修改的对象,包括字符串、元组、数字;不可变类型的对象,对于深浅拷贝毫无影响,最终的地址值和值都是相等的。ui

  • 浅拷贝spa

    拷贝了最外围的对象自己,内部的元素都只是拷贝了一个引用而已。code

    def test_copy_list():
        li = [1, 2, [3, 4]]
        new_li = copy.copy(li)
        print(li == new_li, li is new_li, id(li), id(new_li))
        print(li)
        print(new_li)
        print("**********************************")
        li[2][1] = 5
        print(li)
        print(new_li)
    
        # result:
            # True True 1620049297912 1620049297912
            # (1, 2, [3, 4])
            # (1, 2, [3, 4])
            # **********************************
            # (1, 2, [3, 5])
            # (1, 2, [3, 5])
  • 深拷贝orm

    外围和内部元素都进行了拷贝对象自己,而不是引用对象

    def test_deepcopy_list():
        li = [1, 2, [3, 4]]
        new_li = copy.deepcopy(li)
        print(li == new_li, li is new_li, id(li), id(new_li))
        print(li)
        print(new_li)
        print("**********************************")
        li[2][1] = 5
        print(li)
        print(new_li)
    
        # result:
            # True False 2856182459720 2856182459976
            # [1, 2, [3, 4]]
            # [1, 2, [3, 4]]
            # **********************************
            # [1, 2, [3, 5]]
            # [1, 2, [3, 4]]

列表生成式

  • 基础语法:[exp for iter_var in iterable]
  • 示例:
    li = [1, 2, 3, 4]
    newli = [x*x for x in li]
  • 用于字典生成
    di = {'a': 1, 'b': 2, 'c': 3}
    newdi = {k:v*v for k,v in di.items()}

生成器

  • 经过列表生成式形式,把[]换成()
    def test1():
        li = [1, 2, 3, 4, 5]
        ge = (i*i for i in li)
    
        print(type(ge))
        for i in ge:
            print(i)
            
    test1()
  • 经过yield关键字
    def fib2(max):
        n, a, b = 0, 0, 1
        while n < max:
            yield b
            a, b = b, a+b
            n += 1
    
    for i in fib2(10):
        print(i)
    print(type(fib2(10)))

迭代器

经过for循环,能够从迭代器中取值;迭代器没法回取,只能向前取值。ci

from collections import Iterable

r = range(1, 11)
print(isinstance(r, Iterable))

for ele in r:
    print(ele)

闭包

包的概念:闭包(Closure)是词法闭包(Lexical Closure)的简称,是引用了自由变量的函数。这个被引用的自由变量将和这个函数一同存在,即便已经离开了创造它的环境也不例外。因此,闭包是由函数和与其相关的引用环境组合而成的实体。字符串

  • 在Python中建立一个闭包能够归结为如下三点:
    • 闭包函数必须有内嵌函数
    • 内嵌函数须要引用该嵌套函数上一级namespace中的变量
    • 闭包函数必须返回内嵌函数
  • 示例:
    def greeting_conf(msg):
        def greeting(name):
            print(""+name+"打招呼,说:"+msg)
        return greeting
    
    
    conf = greeting_conf("早上好")
    conf("张三")
    conf("李四")
    
    conf2 = greeting_conf("中午好")
    conf2("张三")
    conf2("李四")
    print(dir(conf2))
    print(conf2.__closure__[0].cell_contents)

装饰器

  • 不带参数的装饰器
    # 装饰者
    def decoratefun(fun): def convert():
            print("before ...............")
            fun() print("after.................")
        return convert
    
    # 被装饰者,此处的@decoratefun 至关于myfunc = decoratefun(myfunc)
    @decoratefun
    def myfunc():
        print("hello world")
    
    myfunc()
  • 带参数
    # 装饰者
    def decoratefun(fun):
        def convert(a, b):
            print("before ...............")
            fun(a, b)
            print("after.................")
        return convert
    
    # 被装饰者,此处的@decoratefun 至关于myfunc = decoratefun(myfunc)
    @decoratefun
    def myfunc(a, b):
        print("参数1是:"+a+";\t参数2是:"+b)
    
    myfunc("hello", "world")
  • 装饰器带参数
    # 装饰者
        def get_decoratorParam(arg):
            def decoratefun(fun):
                def convert(a, b):
                    print("before ...............装饰器的参数是:"+arg)
                    fun(a, b)
                    print("after.................装饰器的参数是:"+arg)
                return convert
            return decoratefun
    
        # 被装饰者,此处的@get_decoratorParam("zzzzzzz") 至关于myfunc = get_decoratorParam("zzzzzzz")(myfunc)
        @get_decoratorParam("zzzzzzz")
        def myfunc(a, b):
            print("参数1是:"+a+";\t参数2是:"+b)
    
        myfunc('1', '2')