zoukankan      html  css  js  c++  java
  • python学习 3笔记

    merge dict

    def merge(defaults, override):
        r = {}
        for k, v in defaults.items():
            if k in override:
                if isinstance(v, dict):
                    r[k] = merge(v, override[k])
                else:
                    r[k] = override[k]
            else:
                r[k] = v
        return r
    

    赋值判断

    k = v1 if [condition] else v2
    

    构建字典

    a = ('a', 'b', 'c')
    c = (1, 2 ,3)
    r = {}
    for k, v in zip(a, c):
        r[k] = v
    

    使字典支持点查找

    class Dict(dict):
        def __init__(self, names=(), values=(), **kw):
            super(Dict, self).__init__(**kw)
            for k, v in zip(names, values):
                self[k] = v
    
        def __getattr__(self, key):
             try:
                return self[key]
             except KeyError:
                raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
    
        def __setattr__(self, key, value):
            self[key] = value
    
    def toDict(d):
        D = Dict()
        for k, v in d.items():
            D[k] = toDict(v) if isinstance(v, dict) else v
        return D
    

    判断是否为函数

    callable(fn)
    

    获取其他模块变量/函数

    mod = __import__(module_name, globals(), locals())
    for attr in dir(mod):
        fn = getattr(mod, attr)
        if callable(fn):
            ......
    

    参数类型判断

    params = inspect.signature(fn).parameters
    for name, param in params.items():
        if param.kind == inspect.Parameter.KEYWORD_ONLY:
        .....
    
    POSITIONAL_ONLY        位置参数
    POSITIONAL_OR_KEYWORD  位置参数或关键字参数
    KEYWORD_ONLY           关键字参数
    VAR_POSITIONAL         可变位置参数 *args
    VAR_KEYWORD            可变关键字参数 **kw      
    

    创建进程

    import multiprocessing, os, time
    
    def whoami(name):
    	print("I'm %s, in process %s" % (name, os.getpid()))
    
    def loopy(name):
    	whoami(name)
    	start = 1
    	stop = 1000000
    	for num in range(start, stop):
    		print("	Number %s of %s. Honk!" % (num, stop))
    		time.sleep(1)
    
    if __name__ == '__main__':
    	whoami('main')
    	#创建进程
    	p = multiprocessing.Process(target=loopy, args=('loopy', ))
    	p.start()
    	time.sleep(5)
    	#终止对应进程
    	p.terminate()
    
    

    打开文件

    file = open('demo.py', 'r', encoding='UTF-8')
    try:
        for line in file:
            print(line, end='')
    except:
        print('讀取檔案發生錯誤')
    finally:
        file.close()
    
    //简化
    with open('demo.py', 'r', encoding='UTF-8') as file:
        for line in file:
            print(line, end='')
    
  • 相关阅读:
    Ubuntu在命令行开启远程桌面
    Qt5编译项目出现GL/gl.h:No such file or directory错误
    硬盘录像机协议与技术汇总
    js判断IP字符串是否正确
    PHP获取原生POST数据
    hdu 5093 二分匹配
    hdu 4435 bfs+贪心
    hdu 4431 绝对值之和最小公式
    hdu 5073 推公式相邻质心转换
    hdu 3657 最小割(牛逼!!!!)总算理解了
  • 原文地址:https://www.cnblogs.com/jinkspeng/p/5280249.html
Copyright © 2011-2022 走看看