What are the coding standards in Python?
Coding standards
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
1. Semicolon
Do not add a semicolon at the end of the line, and do not use A semicolon puts two commands on the same line.
2. Naming
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.
3. Line length
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 = ('这是一个非常长非常长非常长非常长 ' '非常长非常长非常长非常长非常长非常长的字符串')
4. Indentation
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, ... }
5, empty line
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.
6. Spaces
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 }, [ ] )
7. Class
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."""
8. Block comments and line comments
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
9, string
正确示范: 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)
10, import package
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
【Summary】
1. Naming
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
2. Blank
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
3. Statement
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
4. Comments
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Google AI has started to provide developers with access to extended context windows and cost-saving features, starting with the Gemini 1.5 Pro large language model (LLM). Previously available through a waitlist, the full 2 million token context windo

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Pythonempowersbeginnersinproblem-solving.Itsuser-friendlysyntax,extensivelibrary,andfeaturessuchasvariables,conditionalstatements,andloopsenableefficientcodedevelopment.Frommanagingdatatocontrollingprogramflowandperformingrepetitivetasks,Pythonprovid
