Preface
Python learning, first look at Python code specifications, let yourself have a sense of the first, and in the next study slowly develop the habit directory
I. Concise Overview 1, coding If no special circumstances, documents are used UTF-8 code, if no special case, the file head must be added #-*-coding:utf-8-*-identification 2, code format 2.1, Indentation Unified use 4 space to shrink Enter 2.2, line width
Each line of code should be no more than 80 characters (in special cases can be slightly more than 80, but the longest should not exceed 120)
Reason: This is helpful when viewing the diff for side-by-side. Easy to see the code under the console too long it may be flawed design 2.3, quotation marks
Simply put, the natural language uses double quotes, the machine is marked with single quotes, so most of the code should use single quotes natural language with double quotes "..."
For example, error messages, and in many cases Unicode, use single quotes ' ... ' for the U "Hello World" machine logo .
For example, the key regular expression in Dict uses the native double quote r "..." document String (docstring) use three double quotes """......""" 2.4 . Empty lines between the module-level functions and class definitions, and the null row between the class member functions;
Class A:
def __init__ (self):
pass
def-Hello (self): Pass
def main ():
Pass
You can use multiple blank rows to separate multiple groups of related function functions to separate logically related code with empty rows
2.5, codingFile using UTF-8 encoded file header to add #-*-conding:utf-8-*-logo
3. Import StatementThe import statement should be written in a branch
# Correct writing
import OS
import sys
# Not recommended for
import Sys,os
# Correct writing from
subprocess import Popen, PIPE
The import statement should use the
AbsoluteImport
# The correct wording from
foo.bar import Bar
# is not recommended from
Bar Import Bar
The import statement should be placed on the head of the file, after the module description and docstring, before the global variable; the import statement should be sorted in order, separated by a blank line between each group
Import OS
import sys import
msgpack
import zmq
import foo
When you import a class definition for another module, you can use a relative import
From MyClass import MyClass
If a naming conflict occurs, you can use the namespace
Import Bar
import Foo.bar
bar. Bar ()
Foo.bar.Bar ()
4, SpaceEmpty one on either side of the two-dollar operator [=,-, +=,==,>,in,is not, and]:
# The correct wording
i = i + 1
submitted + + 1
x = x * 2-1
hypot2 = x * x + y * y
C = (A + b) * (a-b)
# Not recommended Writing
i=i+1
submitted +=1
x = x*2-1
Hypot2 = x*x + y*y
c = (a+b) * (a-b)
parameter list of the function, and then have a space
# correct writing
def complex (Real, imag): Pass
# deprecated notation
def complex (Real,imag):
Pass
In the parameter list of the function, do not add spaces on either side of the default value
# correct writing
def complex (Real, imag=0.0): Pass
# not recommended for
def complex (real, imag = 0.0):
Pass
After the opening parenthesis, do not add extra spaces before the closing parenthesis
# correct writing
spam (ham[1], {eggs:2})
# Not recommended for writing
spam (ham[1], {eggs:2})
No extra space before the left parenthesis of a Dictionary object
# correct writing
dict[' key '] = List[index]
# Not recommended for writing
dict [' key '] = list [index]
Do not use extra space for Zishing value statements
# correct writing
x = 1
y = 2
long_variable = 3
# deprecated notation
x = 1
y = 2
long_variable = 3
5, line change
Python supports wrapping in parentheses. There are two kinds of situations.
1 indent the second line at the beginning of the bracket
Foo = Long_function_name (Var_one, Var_two,
Var_three, Var_four)
2 indent the second line with 4 spaces, applicable to the start bracket on the line wrap case
def long_function_name (
var_one, Var_two, Var_three,
var_four):
print (Var_one)
Use backslash \ linefeed, two-dollar operator +. etc. should appear at the end of the line; long strings can also be wrapped in this way
Session.query (MyTable). \
filter_by (id=1). \ one
()
print ' Hello, ' \
'%s%s! '%\ '
(' Harry ', ' Potter ')
Prevents compound statements, which include multiple statements in a row:
# The correct wording
Do_first ()
do_second ()
Do_third ()
# is not recommended
Do_first ();d o_second ();d o_third ();
If/for/while Be sure to change lines:
# correct writing
if foo = = ' blah ':
do_blah_thing ()
# Not recommended for writing
if foo = = ' blah ': do_blash_thing ()
6, DocString
The most docstring of the two points in the specification: all public modules, functions, classes, methods, should write DocString. Private methods may not be required, but they should be provided with a block annotation after def. DocString end "" should be exclusive to one row unless this docstring is only a single line.
"" "Return a foobar
Optional Plotz says to frobnicate the Bizbaz" "" "" "" "
Oneline docstring "" "
Second, note
1, Notes
1.1. Block annotation
After the "#" number is empty, the paragraph is separated by a blank line (the "#" number is also required)
# Block Comments
# block Comments
#
Block Comments
# Block notes
1.2, line comments
Use at least two spaces and statements to separate, and be careful not to use meaningless annotations
# correct writing
x = x + 1 # border Bold one pixel
# deprecated notation (meaningless annotation)
x = x + 1 # x plus 1
1.3. Suggestions
In key parts of your code (or more complex), write comments as much as you can.
More important annotation segments, separated by multiple equals, can be more visible, highlighting importance
App = Create_app (name, Options)
# =====================================
# do not add the app routing behavior here such as Get post!!!
# =====================================
If __name__ = = ' __main__ ':
app.run ()
2. Document annotation (docstring)
The docstring of the document generally appears on the head of the module head, function, and class, so that the document can be retrieved from the object's __doc__ object in Python.
Editors and Ides can also give automatic prompts based on docstring. Document comments start and end with "", the first line does not wrap, if there are more than one line, the last line must wrap, the following is Google's docstring style sample
#-*-Coding:utf-8-*-
"" "Example docstrings.
This module demonstrates documentation as specified by the ' Google Python
Style Guide ' _. Docstrings may extend over multiple lines. Sections are created with
a section header and a colon followed by a block of indented text.
Example:
examples can be given using either the ' Example ' or ' examples ' sections
. Sections support any restructuredtext formatting, including literal blocks
::
$ python example_google.py
Section breaks are created by resuming unindented text. Section breaks
are also implicitly created anytime-a new section starts. "" "
Do not define the prototype in the document annotation copy function, but specifically describe its specific content, explain the specific parameters and return values, etc.
# not recommended (don't write function prototypes, etc.)
def function (A, B): ""
function (A, b)-> list "" "
...
# Correct writing
def function (A, B): ""
calculates and returns the average value of the data in the range A through B ""
.
The description of function parameters, return values, and so on, uses the NumPy standard, as shown below
def func (Arg1, arg2): "" "Here is a
summary of the sentence that writes the function (e.g., the average is calculated).
Here is the specific description.
the specific description of the parameter----------
arg1:int
arg1
arg2:int
Arg2 's specific description
return value
-------
int
A specific description of the return value is given in the
--------
otherfunc: Other correlation functions
... Example
--------
example uses the doctest format, the code after ' >>> ' can be automatically run as a test case by the document test tool
>>> a=[1,2,3]
>>> Print [x + 3 for x in a]
[4, 5, 6] "" "
Document comments are not limited to Chinese and English, but do not mix in Chinese and English
Document annotations are not as long as possible, usually one or two words can be clearly explained
Modules, public classes, public methods, can write document annotation, should try to write document comments Three, naming code 1, Module module to use lowercase name, the first letter to keep lowercase, as far as possible without underlining (unless multiple words, and a small number of cases)
# The correct module name Import
decoder
import html_parser
# Not recommended module name
Import decoder
2. Class nameClass name Use Hump (CamelCase) naming style, capitalize first letter, private class can be preceded by an underscore
Class Farm ():
Pass
class Animalfarm (Farm):
Pass
class _privatefarm (Farm):
Pass
Place related classes and top-level functions in the same module. Unlike Java, there is no need to limit a class to a module.
3. Functionfunction name All lowercase, if have more than one word, use underline to separate
def run ():
pass
def run_with_env ():
Pass
The private function adds an underscore before the function _
Class person ():
def _private_func ():
Pass
4, variable nameVariable names as small as possible, with multiple words, separated by an underscore
if __name__ = = ' __main__ ':
count = 0
school_name = '
Constants are all uppercase and, if multiple words are used, are separated by underscores
Max_client =
max_connection = 1000
connection_timeout = 600
5, ConstantConstants are named with an underscore-delimited
max_overflow = Class Foobar:def Foo_bar (Self, Print_): Print (Print_)