current position:Home>Python programming specification
Python programming specification
2022-07-24 18:16:29【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
1,Python Programming specification
> code
be-all Python Script files should be marked with
# -*- coding:utf-8 -*-
Used to set the editor , Save as by default utf-8 Format .
> notes
The industry generally agrees that Python There are two types of comments ,
One is by # At the beginning “ real ” notes , for example , It is used to indicate why the current implementation is selected and the principles and difficulties of this implementation
The other is docstrings, for example , Used to show how to use this package 、 modular 、 class 、 function ( Method ), Even use examples and unit tests to adhere to the principle of appropriate annotation .
Do not comment on the code without technical difficulties , The code with technical difficulties must be annotated . But unlike notes , It is recommended for each package 、 modular 、 class 、 function ( Method ) Write
docstrings, Unless the code is clear at a glance , It's simple .
> Indent
Python Rely on indentation to determine the level of code blocks , There are mainly two kinds of blank characters at the beginning of a line :tab and Space , However, it is strictly forbidden to mix the two . If you use tab Indent , Set up tab by 4 A space .
> Space
Spaces in Python It makes sense in the code , because Python The syntax of depends on indentation , Spaces at the beginning of a line are called leading spaces . In this section, we will not discuss the content related to leading spaces , Only non leading spaces are discussed . Non leading spaces in Python There is no meaning in the code , But properly adding non leading spaces can improve the readability of the code .
1) In binary arithmetic 、 Add spaces before and after logical operators : Such as
a = b + c;
2) Do not add spaces after the unary prefix operator , Such as
if !flg: pass;
3) “:” When used at the end of a line, there is no space before or after , Such as branching 、 loop 、 Function and class definition language ; Use it at the end of a non line with spaces at both ends , Such as :
dict Object definition
d = {'key' : 'value'}
4) Brackets ( With parentheses 、 Square brackets and curly braces ) No spaces before and after , Such as :
do_something(arg1, arg2)
instead of do_something( arg1, arg2 )
5) Don't use commas 、 A semicolon 、 A colon is preceded by a space , But they should be followed by ( Except at the end of the line )
6) Don't use spaces to align multiple lines vertically , Because it's going to be a maintenance burden ( Apply to :,#,= etc. )
> Blank line
Appropriate blank lines help to increase the readability of the code , Blank lines can refer to the following guidelines :
1) In the class 、 Empty lines between the definitions of functions ;
2) stay import Add blank lines between different types of modules ;
3) Add blank lines between logical paragraphs in a function , That is to put the relevant code together , As a logical paragraph , Paragraphs are separated by blank lines ;
> Line breaks
Although the current widescreen display can display more than 256 Column characters , However, this specification still insists that the maximum length of the line shall not exceed 80 A standard of characters . There are several ways to fold long lines :
1) Change the long variable name to a short one , Such as :
this.is.a.very.long.variable_name = this.is.another.long.variable_name
Should be changed to :
variable_name1 = this.is.a.very.long.variable_name
variable_name2 = this.is.another.variable_name
variable_name1 = variable_name2s
2) Python Will put parentheses 、 The lines in brackets and curly brackets are connected implicitly , You can take advantage of this feature . If needed , You can add an extra pair of parentheses around the expression
3) Add a continuation character to the long line to forcibly break the line , The position of the line break should be before the operator , And one more indent after line feed , So that when the maintainer looks at the code, he can see the beginning of the code line and judge that there is line feed here , Such as :
if color == WHITE or color == BLACK \
or color == BLUE: # Be careful or The operator is at the beginning of the new line, not at the end of the old line
do_something(color);
> character string
1. Avoid using in a loop + and += Operator to accumulate strings . Because strings are immutable , Doing so creates unnecessary temporary objects , And it leads to quadratic rather than linear run times .
As an alternative , You can add each substring to the list , And then at the end of the loop, use .join Connection list .( You can also write one for each substring cStringIO.StringIO In cache
2. Use triple double quotes instead of triple single quotes for multiline strings . But be careful , It's usually clearer to use implicit lines to connect , Because multiline strings don't indent with the rest of the program .
> name
Consistent naming can save developers a lot of trouble , Proper naming can greatly improve the readability of the code , Reduce maintenance costs .
>> Constant
Constant names all uppercase , Connect words by underscores , Such as
WHITE = 0XFFFFFF
THIS_IS_A_CONSTANT = 1
>> Variable
Variable names are all lowercase , Connect words by underscores , Such as
color = WHITE
this_is_a_variable = 1
Private class members are identified with a single underscore prefix , Multiple definition public members , Define fewer private members .
Variable name should not have type information , because Python Is a dynamically typed language . Such as iValue、names_list、dict_obj Waiting is a bad name .
>> function
The naming rules of function names are the same as variable names .
>> class
Use capital letters for class names ( Such as CapWords, namely Pascal style ), Do not use underscores to connect words . Such as :
class ThisIsAClass(object):pass
>> modular
Module names are all lowercase , For modules used in the package , You can add an underscore prefix , Such as
module.py
_internal_module.py
>> package
The naming convention of the package is the same as that of the module
>> abbreviation
Try to use the word spelled as much as possible , There are two abbreviations : 1) Common abbreviations , Such as XML、ID etc. , It should also be named with only uppercase initials , Such as
class XmlParser(object):pass
2) Long words in naming , Abbreviate a word . In this case, the contracted abbreviation should be used , Such as removing vowels 、 The first character containing consonants, etc , for example :
function Abbreviation for fn
text Abbreviation for txt
object Abbreviation for obj
count Abbreviation for cnt
number Abbreviation for num, etc. .
>> Specific nomenclature
Mainly refers to __xxx__ Systematic retention word nomenclature of form . This naming can also be used in projects , It means that variables in this form are read-only , Try not to overload this form of class member function . Such as
class Base(object):
def __init__(self, id, parent =None):
self.__id__ = id
self.__parent__ = parent
def __message__(self, msgid):
# … A little
among __id__、__parent__ and __message__ System reserved word nomenclature is adopted .
>> Import format
- import The order of the , First import Python Built-in module , Again import Third-party module , Last import Other modules in the self-developed project ; These modules are separated by blank lines .
- Every import Should have a monopoly on .
- Do not use from module import *, Unless it is import Constant definition modules or other modules that you ensure do not have namespace conflicts .
> assignment
For assignment language , The main thing is not to do unnecessary alignment , Such as :
a = 1 # This is a line comment
variable = 2 # Another line comment
fn = callback_function # Or comment
There is no need to do this alignment , For two reasons : First, this alignment will disturb the attention of programming , The brain has to deal with two things at the same time ( Programming and alignment ); Second, it is difficult to read and maintain in the future , Because the horizontal field of vision of the human eye is very narrow , It is difficult to treat three fields as one line , And adding a longer variable name during maintenance will also break the alignment . It is better to write directly like this :
a = 1 # This is a line comment variable = 2 # Another line comment fn = callback_function # Or comment
> sentence
Usually, each statement should have a single line . however , If the test result and the test statement are on the same line , You can also put them on the same line . If it is if sentence , Only in the absence of else Only when you can do this . Specially , Never be right about try/except To do so , because try and except It can't be on the same line .
2, Reference material
3, Document modification history
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/124465.html Link to the original text :https://javaforall.cn
copyright notice
author[Full stack programmer webmaster],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/203/202207211150281795.html
The sidebar is recommended
- [Python web] the use of Python to connect to third-party database series redis and redis
- [Python web] Python connection to third-party database series using pymongo to connect mongodb
- [Python web] Python connects to third-party database series using pymysql to MySQL
- Python graphics development Kivy small problems
- Python tool method 33 easily realizes the integration of multiple losses based on the lossfusion class
- Summary of Python automated test interview questions (I) (continuously updated)
- Python office software automation, 5 minutes to master openpyxl operation
- Python interview question - [bisection search] given a sorted array of non repeating integers and a target value, if the target is found, the index is returned.
- Python test development django-197.django-celery-beat scheduled task
- Play with Python tips [i for I in range()] + [or]
guess what you like
[leetcode scribble Python] 15. Sum of three numbers
[leetcode scribble Python] 16. The sum of the nearest three numbers
Python38 failed to install jsonpath. Problem solving
Python test development django-193. use the supervisor background to start the celery service (worker/beat)
Python test development django-194.addcomments module generates MySQL table field comments
Python test development django-196.python 3.8 + django2 + celery5.2.7 environment preparation
Python test development django-195.django add favicon.ico Icon
[leetcode scribble Python] 122. The best time to buy and sell stocks II
Common methods of saving pictures in Python
Python word frequency analysis
Random recommended
- Pandas uses to_ The datetime function converts a time string into a time object, defines the format of the input time string (%m/%d/%y%i:%m:%s%p), and specifies the format of the output time object using dt.strftime
- Python list
- Python list memory deep copy and shallow copy
- Drawing pie chart in Python
- Batch rename of Python files
- Python Tkinter - Chapter 3 Tkinter (window creation and pack layout)
- Python Tkinter - Chapter 3 (3) place layout
- Python Tkinter - Chapter 3 (2) grid layout
- [Python question brushing] day7~ efficient exercise of Niuke question bank
- Go and python compare processes, go and operating system compare scheduling
- Xiaolang: Python logging log module learning - log output to console and file at the same time
- [QT for Python] control display (controls without parent controls are not displayed by default)
- Tsfresh: a python toolkit for automatic extraction of temporal features with excellent performance
- Python office software automation, 5 minutes to master openpyxl operation
- The sixth Django training
- Mekol Studio - the third training of Django
- Baidu translation in Python
- Python turtle drawing Pythagorean tree
- Python os.path.getsize()
- Python Wu Enda deep learning assignment 16 -- face recognition
- What types of data structures does pandas have?
- Connect to the database using Python
- Python crawler JS reverse x-bogus, signature encryption algorithm, AST theory
- Python: implement the palindrome number algorithm (with complete source code)
- Python: implement the algorithm of merging two lists (with complete source code)
- Python: implement the intermediate element algorithm for finding linked lists (with complete source code)
- Python: implement the reverse printing linked list algorithm (with complete source code)
- Python: implementation of single linked list algorithm (with complete source code)
- Python: implement skip list skip algorithm (with complete source code)
- Python: implement the linked list exchange node algorithm (with complete source code)
- Python: implement the circular queue linked list algorithm (with complete source code)
- Python: implement circular queue algorithm (with complete source code)
- Python: implement double ended queue algorithm (with complete source code)
- Python: implement the queue algorithm represented by a list (with complete source code)
- Python: implement link queue algorithm (with complete source code)
- Python: implement priority queue algorithm (with complete source code)
- Python: implement the queue algorithm represented by pseudo stack (with complete source code)
- Python: implement balanced parentheses balanced parentheses expression algorithm (with complete source code)
- Python: realize the algorithm of calculating the input formula using stack (with complete source code)
- Python Django patient tracking treatment information management system - project source code Vue