• 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='')
    
  • 相关阅读:
    干掉你的老板(小游戏)
    SEO优化数据系列表(图)
    javascript动态加载三
    javascript动态加载二
    截屏
    vimdiff
    pscp scp ftp samba windows send files to linux
    login windows 10 with passwd instead of pin
    modify requirements.txt
    整片注释 ,shell
  • 原文地址:https://www.cnblogs.com/jinkspeng/p/5280249.html
Copyright © 2020-2023  润新知