The reason why Python coding standards are important can be summed up in one sentence:Unified coding standards can improve development efficiency.
ps.python code writing must basically follow the PEP8 style
Do not add a semicolon at the end of the line, and do not use A semicolon puts two commands on the same line.
module_name, package_name, ClassName, method_name
Names that should be avoided
Single character names, except counters and iterators.
Hyphens (-) in package/module names
Start and end with double underscore The name (Python reserved, such as __init__)
Naming convention
The so-called "internal" means Only available within the module, or, protected or private within the class.
Starting with a single underscore (_) indicates that the module variable or function is protected (not used when using import * from Will contain)
Instance variables or methods starting with a double underscore (__) indicate private within the class.
Relate the relevant class and top-level Functions are placed in the same module. Unlike Java, there is no need to limit one class to one module.
Use words starting with capital letters (such as CapWords, Pascal style) for class names, But module names should be in lowercase and underlined (such as lower_with_under.py). Although there are many existing modules using names similar to CapWords.py, this is no longer encouraged because if the module name happens to be the same as the class name Consistent, this will cause trouble.
No more than 80 characters per line
Except for the following situations:
URLs in long import module statement comments
Do not use backslashes to connect lines.
Python will implicitly connect the lines enclosed in parentheses, square brackets and curly braces. You can take advantage of this feature. If necessary, you can add a pair around the expression Extra parentheses.
Recommendation:
foo_bar(self, width, height, color='black', design=None, x='foo', emphasis=None, highlight=0) if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong'):
If a text string does not fit on one line, you can use parentheses to implement implicit line connection:
x = ('这是一个非常长非常长非常长非常长 ' '非常长非常长非常长非常长非常长非常长的字符串')
Use 4 spaces to indent code
Never use tabs, or mix tabs and spaces. In the case of line concatenation, you should either vertically align wrapped elements (see :ref:`line length
# 与起始变量对齐 foo = long_function_name(var_one, var_two, var_three, var_four) # 字典中与起始值对齐 foo = { long_dictionary_key: value1 + value2, ... }
Top level Two blank lines between definitions, one blank line between method definitions
Two blank lines between top-level definitions, such as function or class definitions. There should be one blank line between method definitions, class definitions and the first method. . In functions or methods, if you think it is appropriate in some places, leave a blank line.
Use spaces on both sides of punctuation in accordance with standard formatting specifications
There should be no spaces within the brackets.
Use spaces on both sides of the punctuation according to standard formatting conventions
正确示范: spam(ham[1], {eggs: 2}, [])
错误示范: spam( ham[ 1 ], { eggs: 2 }, [ ] )
The class should be in its definition There is a docstring describing the class below. If your class has public attributes (Attributes), then the documentation should have an attributes (Attributes) section. And it should follow the same format as the function parameters.
class SampleClass(object): """Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """ def __init__(self, likes_spam=False): """Inits SampleClass with blah.""" self.likes_spam = likes_spam self.eggs = 0 def public_method(self): """Performs operation blah."""
The most important parts of the code to write comments are those technical parts. If you must explain it during the next code review, then you You should write comments for it now. For complex operations, you should write several lines of comments before the operation starts. For code that is not self-explanatory, comments should be added at the end of the lines.
# We use a weighted dictionary search to find out where i is in # the array. We extrapolate position based on the largest num # in the array and the array size and then do binary search to # get the exact number. if i & (i-1) == 0: # true iff i is a power of 2
In order to improve readability , comments should leave at least 2 spaces away from the code.
On the other hand, never describe the code. Assume that the person reading the code knows Python better than you do, he just doesn’t know what your code is doing.
# BAD COMMENT: Now go through the b array and make sure whenever i occurs # the next element is i+1
正确示范: x = a + b x = '%s, %s!' % (imperative, expletive) x = '{}, {}!'.format(imperative, expletive) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n)
错误示范: x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = imperative + ', ' + expletive + '!' x = 'name: ' + name + '; score: ' + str(n)
Each import should be on its own line
正确示范: import os import sys
错误示范: import os, sys
The import should always be placed at the top of the file, located in the module comment and docstrings, before module global variables and constants. Imports should be grouped in order from most common to least common:
Standard library imports Third-party library imports Application-specific imports
Functions, variables and properties should be spelled in lowercase words. Use _ to connect, do not follow camel case naming convention
Classes and exceptions should be capitalized, do not use _ to connect
Protected instance attributes , should start with a single underscore
The private properties of the instance should start with a double underscore
Module-level variable words must be capitalized, with the middle Separate with single underscores
Variables should be as meaningful as possible
Each level of indentation related to syntax is represented by 4 spaces
When assigning, there must be a space on both sides of the equal sign
Each The number of characters occupied by one line should not exceed 79. In actual operation, you should try not to let the line scroll bar of the code editor be displayed
When using functions for functional programming, there should be two blank lines between functions
For functions in a class, there should be one blank line between functions
If functions and classes are at the same level, there should be two empty lines between them
For long expressions that exceed the specified number of characters per line formula, you should hit Enter to indent, usually all lines except the first line should be indented by 4 spaces again based on the original
Do not use == when judging whether a variable is None, False or True. Use is. For example, if a is None
The import statement should be placed at the beginning of the sentence. When importing, try to use absolute import instead of relative import, and it is best to specify a specific function of the corresponding module when importing. For example, from datetime import datetime
The module should be imported according to Classification of standard library modules, third-party modules and self-used modules
When detecting that the container is not empty, the if container name should be used, for example, lists = [] if lists
Use inline form of negative words, do not put the negative word in front of the entire expression, for example, it should be if a is not None instead of if not a is None
For functional descriptions of some important code blocks, single-line comments
should be used for the entire module function. The description should use multi-line comments
The detailed description of the function and usage of the class or function should use the documentation string
python Please use English as much as possible
The above is the detailed content of What are the coding standards in Python?. For more information, please follow other related articles on the PHP Chinese website!