python项目相关技巧

1、模块控制
先执行:pip freeze > requirements.txt
再执行:pip install -r requirements.txt

2、新建python package和directory的区别
directory:存放资源
python package:目录中的方法可以被引用

3、命名规范
常量:使用大写,如果需要可以加下划线,如:THIS_IS_A_CONSTANT = 1
普通变量:使用小写,如果需要可以加下划线,如:this_is_a_variable = 1
私有变量:前缀有下划线
函数和方法:使用小写,如果需要可以加下划线
类:驼峰式命名,一般使用大驼峰
模块:模块名称小写,不带下划线
包:全小写,可使用下划线
文件:全小写,可使用下划线

4、创建py文件时开头注释的设置
File——Settings——Editor——File and Code Templates——Python Script
然后写入开头注释即可

5、获取项目根目录

def root_path():
    p = os.getcwd()
    while True:
        if os.path.split(p)[1] == '目标路径':
            break
        p = os.path.dirname(p) 
    return p

6、巧用eval

data = {"1": {"2": {"3": "测试"}}}


def aaa(*args):
    a = "data{}".format(''.join(['["{}"]'.format(i) for i in args]))
    return eval(a)


print(aaa("1"))
print(aaa("1", "2"))
print(aaa("1", "2", "3"))

# 运行结果
# {'2': {'3': '测试'}}
# {'3': '测试'}
# 测试

  

原文地址:https://www.cnblogs.com/yinwenbin/p/12228653.html