Python代码风格
最近发现了一个不错的参考网站
官方的Style Guide for Python Code.
有关编写有用的文档字符串的准则,请参见:Docstring Conventions.
本文摘自以上两个网站以及《Data Structures and Algorithms in Python》
- Python code blocks are typically indented by 4 spaces.
- Use meaningful names for identifiers.
- Classes (other than Python’s built-in classes)
- a singular noun, and should be capitalized (e.g.,
Date
rather thandate
orDates
). - When multiple words are concatenated to form a class name (e.g.,
CreditCard
).
- a singular noun, and should be capitalized (e.g.,
- Functions, including member functions of a class
- should be lowercase.
- If multiple words are combined, they should be separated by underscores (e.g.,
make_payment
). - should typically be a verb that describes its affect.
- However, if the only purpose of the function is to return a value, the function name may be a noun that describes the value (e.g.,
sqrt
rather thancalculate_sqrt
).
- Names that identify an individual object (e.g., a parameter, instance variable, or local variable)
- should be a lowercase noun (e.g.,
price
). - Occasionally, we stray from this rule when using a single uppercase letter to designate the name of a data structures (such as tree
T
).
- Identifiers that represent a value considered to be a constant - using all capital letters and with underscores to separate words (e.g.,
MAX_SIZE
). - Recall from our discussion of encapsulation that identifiers in any context that begin with a single leading underscore (e.g.,
_secret
) are intended to suggest that they are only for “internal” use to a class or module, and not part of a public interface.
- should be a lowercase noun (e.g.,
- Classes (other than Python’s built-in classes)
- Comments
- In-line comments are good for quick explanations
if n % 2 == 1: # n is odd
- Multiline block comments are good for explaining more complex code sections. In Python, these are technically multiline string literals, typically delimited with triple quotes (
”””
), which have no effect when executed. In the next section, we discuss the use of block comments for documentation.
- In-line comments are good for quick explanations
小结
Types of Identifiers | Examples |
---|---|
Classes (other than Python’s built-in classes) | Date , CreditCard |
Functions, including member functions of a class | make_payment , sqrt |
Names that identify an individual object (e.g., a parameter, instance variable, or local variable) | price , a tree T |
Identifiers that represent a constant | MAX_SIZE |
Identifiers that are only for “internal” use to a class or module, and not part of a public interface | _secret |