zoukankan      html  css  js  c++  java
  • Python高手之路 ------读书有感

    最近忙中偷闲把前些年买的《Python高手之路》翻了出来,大致看完了一遍,其中很多内容并不理解,究其原因应该是实践中的经验不足,而这对于现如今的我仍是难以克服的事情,对此也就只能说是看会了多少算多少了,但是在自己理解的那一部分之中本人还是发现了很多以前没有见过的东西,对此本博主将其记录下来,以为自己日后翻阅同时也共享给网上的众多网友。

    1. collections.defaultdict

    collections  为Python中的一个高级模块,其中collections模块中有一个 默认字典( collections.defaultdict ) 的类型,调用该类时对其初始化一个类对象,该类对象所生成的对象必为可调用,如:list,set等,若不赋值则默认为None。

    可以看到对 defaultdict 所生成的对象进行赋值时 返回的自动为 生成该对象时 赋予的类对象所生成的 对象。

    有此可见对该类型的调用可以自动将调用的赋值作为key, 其返回的就是默认生成对象,对于该对象我们可以对其进行操作。

    2. memoryview

    import copy
    
    x=str(range(10000000))
    
    @profile
    def fun():
        w=x[1:-1]
    
        view=memoryview(x)
    
        limited=view[1:-1]
    
    
    if __name__=="__main__":
        fun()

     

    由此,可见 memoryview  和C语言中的指针颇有相似, 该操作对 字符串  和  字节类型的  变量进行切片  不增加其它  内存  开销。

    根据 memoryview  改变原对象中  变量的值:

    3.  memory_profiler

    memory_profiler  是Python中的一个内存耗费显示模块, 该模块不属于标准库, 因此需要额外安装。

    该模块使用是对要检测的模块中函数加入  @profile  装饰器, 即可实现对该函数调用时内存耗费情况的检测。

    4. 装饰器  functools.wraps

    def is_admin(f):
        def wrapper(*args, **kwargs):
            if kwargs.get("username")!='admin':
                raise Exception("This user is not allowed to get food!")
            return f(*args, **kwargs)
        return wrapper
    
    
    def foobar(username="someone"):
        """Do crazy stuff."""
        pass
    
    
    print foobar.func_doc
    print foobar.__name__

    修改如下:

    def is_admin(f):
        def wrapper(*args, **kwargs):
            if kwargs.get("username")!='admin':
                raise Exception("This user is not allowed to get food!")
            return f(*args, **kwargs)
        return wrapper
    
    @is_admin
    def foobar(username="someone"):
        """Do crazy stuff."""
        pass
    
    
    print foobar.func_doc
    print foobar.__name__

    由上可知, 使用装饰器对函数进行包装后 函数原有的一下特性及信息丢失。

    import functools
    
    
    def is_admin(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            if kwargs.get("username")!='admin':
                raise Exception("This user is not allowed to get food!")
            return f(*args, **kwargs)
        return wrapper
    
    @is_admin
    def foobar(username="someone"):
        """Do crazy stuff."""
        pass
    
    
    print foobar.func_doc
    print foobar.__name__

    使用 functools.wraps  装饰器  对 包装函数 中的返回函数进行修饰, 将原函数的信息复制给该函数。

     写于  大连理工大学  软件学院

  • 相关阅读:
    react 实现路由按需加载
    vue-router 与 react-router 设计理念上的区别
    create-react-app 知识点
    ElementUI(vue UI库)、iView(vue UI库)、ant design(react UI库)中组件的区别
    create-react-app 搭建的项目中,让 antd 通过侧边栏导航 Menu 的 Menu.Item 控制 Content 部分的变化
    react-router v4.0 知识点
    prop-types:该第三方库对组件的props中的变量进行类型检测
    002_mtr_a network diagnostic tool
    006_netstat中state详解
    003_监测域名证书过期时间
  • 原文地址:https://www.cnblogs.com/devilmaycry812839668/p/7681731.html
Copyright © 2011-2022 走看看