Python 变量和方法的正确大小写和格式
所以我知道有些语言有预期的约定。
PHP - underscore_case()
[大部分情况下,lolo]
Java - camelCase()
C# - PascalCase()
等。
什么是“Pythonic” “命名约定?我知道这最终并不重要,只是想知道是否有大多数模块完成的“最佳实践”方式。
So I know some languages have expected conventions.
PHP - underscore_case()
[for the most part, lolo]
Java - camelCase()
C# - PascalCase()
etc.
What's the "Pythonic" naming convention? I know it doesn't matter in the end but just wondering if there is a "best practice" way that most modules are done in.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个词:PEP 8。
PEP 8 是(事实上的)Python 风格指南。本文档中的一些亮点(我故意遗漏了一些内容;请阅读原始文档以了解详细信息):
包和模块名称:全小写名称。如果可以提高可读性,可以在模块名称中使用下划线。
类名称:类名称几乎毫无例外地使用 CapWords 约定。*
全局变量名称:约定与函数大致相同。
函数名称:函数名称应小写,必要时用下划线分隔单词以提高可读性。仅在已成为流行风格的上下文中(例如
threading.py
)才允许混合大小写,以保持向后兼容性。方法名称和实例变量:小写,单词之间用下划线分隔,以提高可读性。仅对非公共方法和实例变量使用一个前导下划线。
常量:全部用大写字母书写,并用下划线分隔单词。示例包括。
Two words: PEP 8.
PEP 8 is the (de facto) Python style guide. Some highlights from this document (I left some stuff out on purpose; go read the original document for the ins and outs):
Package and Module Names: All-lowercase names. Underscores can be used in the module name if it improves readability.
Class Names: Almost without exception, class names use the CapWords convention.*
Global Variable Names: The conventions are about the same as those for functions.
Function Names: Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style (e.g.
threading.py
), to retain backwards compatibility.Method Names and Instance Variables: Lowercase with words separated by underscores as necessary to improve readability. Use one leading underscore only for non-public methods and instance variables.
Constants: Written in all capital letters with underscores separating words. Examples include.
阅读PEP 8。
它是 Python 代码的风格指南,由 Python 的创建者 Guido van Rossum 编写。
顺便说一句,您问题的答案是对变量和函数名称使用
underscore_case
,对类使用PascalCase
。Read PEP 8.
It's a style guide for Python code, written by Python's creator, Guido van Rossum.
Incidentally, the answer to your question is to use
underscore_case
for variables and function names, andPascalCase
for classes.七个字:Google 代码之夏 Python 风格指南
Seven words: Google Summer of Code Python Style Guide