栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python编码规范踩过的坑

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python编码规范踩过的坑

Python编码规范踩过的坑
  • 1.try.....except.....
  • 2.whitespace
  • 3.indent
  • 4. 与 ()
  • 5. and与or

PEP8编码规范

1.try…except…

E722 do not use bare ‘except’, specify exception instead
对于except,按照规范最好不要使用bare except, 而是使用具体的except
例如:

// correct
try:
    user = User.objects.get(pk=user_id)
    user.send_mail('Hello world')
except User.DoesNotExist:
    logger.error('The user does not exist with that ID')
//No specification
try:
    user = User.objects.get(pk=user_id)
    user.send_mail('Hello world')
except:
    logger.error('The user does not exist with that ID')
2.whitespace

E226 missing whitespace around arithmetic operator
当使用算术运算符后要注意算术运算符周围的空格。例如:

// correct
list = [0, 1, 2, 3, 4]
for i in range(len(list) / 2):
	print(list)
//No specification
list = [0, 1, 2, 3, 4]
for i in range(len(list)/2):
	print(list)
3.indent

E125 continuation line with same indent as next logical line
有时候为了追求上下行对齐,在换行后,延续行与下一个逻辑行具有相同的缩进时会引发该错误。

// correct
if user is None and user.admin or 
        user.name == 'Blue':
    ohter = 'hah'
//No specification
if user is None and user.admin or 
    user.name == 'Blue':
    ohter = 'hah'

E131 continuation line unaligned for hanging indent

// correct
if user is None and user.admin or 
        user.name == 'Blue' or 
        user.age == '17':
    ohter = 'hah'
//No specification
if user is None and user.admin or 
    user.name == 'Blue' or 
    	user.age == '17':
    ohter = 'hah'
4. 与 ()

在python中如果一句写不下可以使用换行符或者()但是不能两个一起用

// correct
if user is None and user.admin or 
        user.name == 'Blue':
    ohter = 'hah'
//No specification
if (user is None and user.admin or 
    	user.name == 'Blue'):
    ohter = 'hah'
5. and与or

and与or一般常用与条件判断中,如果想要达到预期效果需要小心使用

// print的结果为yes
a = 3
b = 2
if a == 3 or a == 2 and b == 1:
	print('yes')
else:
	print('no')
//print的结果为no
a = 3
b = 2
if (a == 3 or a == 2) and b == 1:
	print('yes')
else:
	print('no')

持续更新中。。。。。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675343.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号