我最近开始使用 Python/Django,并且听说了 PEP 8 约定。看完PEP8我对如何“设计”我的代码有了更好的认识,但我学习了 Java 编程,而且我过去只是做我喜欢做的事。你能建议如何将我的示例放入 PEP-8 中吗?非常感谢。
result = urllib.urlretrieve(
"https://secure.gravatar.com/avatar.php?"+
urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)
})
)
尝试下载代码样式 linters,例如 pep8(一种检查您的代码以查看其是否符合 PEP 8 要求的程序)或 pylint。您可以在此处找到更全面的 Python 样式检查器列表和比较:What are the comprehensive lint checkers for Python?
事实上,网上有一个 pep8 检查器:http://pep8online.com/
如果我们通过它运行您的代码,它会告诉您:
Code Line Column Text
E126 2 29 continuation line over-indented for hanging indent
E225 2 70 missing whitespace around operator
E126 4 45 continuation line over-indented for hanging indent
E501 4 80 line too long (90 > 79 characters)
W292 7 30 no newline at end of file
您的代码的固定版本看起来更像这样:
result = urllib.urlretrieve(
"https://secure.gravatar.com/avatar.php?" +
urllib.urlencode({
'gravatar_id': hashlib.md5(email).hexdigest(),
'size': srt(size)
})
)
本质上,您违反 PEP 8 的主要行为是缩进过多。单个缩进就可以了——您不需要与函数调用的左括号对齐。 Python 还坚持您的行不要超过 80 个字符,但修复过度缩进也解决了该问题。