Python- coding conventions related

Python style guide

Semicolon: Do not add a semicolon end of the line, do not use semicolons two commands on the same line.

Line length: each line is not more than 80 characters

Brackets: Ningquewulan parentheses

Indent: with four spaces to indent your code

Blank lines: Blank lines between the top two definitions, one blank line between method definitions

Note: Be sure to modules, functions, annotation using the correct method and style within the line

Class: If a class does not inherit from other classes, it is explicit from the object nested class inherits the same.

String: even if the parameter is a string, formatted using methods% or operator but can not be generalized format strings, you need between +% and well determined.

File and sockets: At the end of the file and sockets, explicitly close it.

Import format: it should be a separate line for each imported. Module, three libraries, the specified program

Statement: Each statement should normally separate line

Access Control: In Python, trivial and less important for access functions, should direct the use of public variables to replace them, to avoid the extra function call overhead when adding more features, you can use property (property). consistent syntax (Translator's Note: emphasis on object-oriented programmers to see this package may be very offensive, because they have been taught:! all member variables must be private in fact, it really is a bit of trouble ah try to accept it Pythonic philosophy)

命名:module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.

The name should be avoided: one-character names, in addition to the counter and iterators, package / module name hyphen (-) at the beginning and end of the double underscore name (Python reserved, for example, __init__)

Naming Conventions: the so-called "internal (Internal)" indicates only available within the module, or in the class is protected or private.

Single underscore (_) at the beginning of a block of variable or function is protected (it does not include the use of import * from).

Double-underlined (__) method or instance variables represents the beginning of the kind of private.

The related classes and top-level functions in the same module. Unlike Java, a class is not necessary to limit a module.

The use of class names begin with a capital letter word (such as CapWords, namely Pascal style), but the module name should be in lower case underlined the way (such as lower_with_under.py). Although there are many existing modules such use similar CapWords.py named, but now is not encouraged, because if it happens module name and the name of the same class, which will be annoying.

Main: Even a script file is used as intended, should also be imported and simple import should not lead to the main function of the script (main functionality) is executed, which is a side effect of the main functions should be placed. a main () function.

What is PEP8, tied with PEP8 Coding Standards

Python Enhancement Proposal (Python enhancement proposals), PEP8 is a programming specification content are some suggestions on how to make your program more readable;

1, do not a multiple import libraries, such as importos, sys is not recommended

2, two blank spaces defined between the top, such as functions or class definitions. The method defined between the class definition and the first method, a blank line should

3, triple quotes annotation; no space before the comma, colon, semicolon.

4, four spaces of indentation (editor can accomplish this function), do not use Tap, Tap and more can not mix spaces

Zen of Python understand it?

Perl programming language has long dominated in the Internet field dominance, the early majority are interactive websites using Perl scripts, Perl is based on the motto "solution to the problem have more", too much emphasis on flexibility will lead to large-scale project difficult to maintain , it is the view of the problems encountered in the Perl language, experienced programmers to write Python code will have to avoid complicated to simple ideas, culminating in one day by a man named Tim Peters written out, that is, "Python Zen." It is not out of the hands of the founder of Python, but has been officially recognized as a programming principle.

View in the editor. New .py file, the file name taken lightly, type import this, and run the code, there will be console output "Python's Zen":

1. Beautiful is better than ugly. United States is better than ugly.

2. Explicit is better than implicit. Implicit than explicit.

3. Simple is better than complex. Simple is better than complex.

4. Complex is better than complicated. Good complexity better than messy.

5. Flat is better than nested. Nesting better than flat.

6. Sparse is better than dense. Intervals rather than compact.

7. Readability counts. Emphasis on readability.

8. Special cases aren’t special enough to break the rules.

9. Although practicality beats purity.

Special case is not sufficient to break the rules, even if the exception is very practical, and do not violate these rules.

10. Errors should never pass silently.

11. Unless explicitly silenced.

Error is normal, have the courage to face and correct, if you are sure you want to change, you can also choose to pass.

12. In the face of ambiguity, refuse the temptation to guess.

13. There should be one-- and preferably only one --obvious way to do it.

14. Although that way may not be obvious at first unless you’re Dutch.

Face a variety of possible (ambiguity), do not try to guess, but should try to find one of the best is the only obvious solution. However, if you are not the parent of Python, then this solution start It may not be obvious.

15. Now is better than never.

16. Although never is often better than right now.

Maybe they do not do better, but the first hands to meditate.

17. If the implementation is hard to explain, it’s a bad idea.

18. If the implementation is easy to explain, it may be a good idea.

If you can not explain to people aware of your program, it is certainly not a good program; and vice versa.

19. Namespaces are one honking great idea – let’s do more of those!

Namespace is a wonderful idea, we should be more use.

The end of the phrase: you can see, Python Zen is not only talking about the programming philosophy, but philosophy of life skills life. The original love every good programmer code is a philosopher. Python's origin is not Java, Go so highly anticipated, early Python, under heavy siege Java, PHP, JS, C ++, etc., even though the audience is not extensive, but still survive, mainly because the design philosophy of Python that it has the full vitality. Under the guidance of this design philosophy, Python and gradually developed into a special friendship concise, easy to use, powerful language.

Docstring understand it?

docstring is a bunch of comments in the code. Any programming language has a comment, but the Python docstring can be directly output by a help function for documentation formats, this on the powerful. Code written, written comments, a help call, there is a document read.

docstring can be written in three places: the module or pack, objects, functions.

Learn what types of annotations?

https://www.jianshu.com/p/b863c4b29b52

Python naming objects, methods, or the like e.g.

File name: all lowercase, you can use an underscore

Package: It should be short, lowercase names. If underscore can be added to improve readability. As mypackage.

Module: the same packet specification. As mymodule.

Class: always use the capitalized word string. Such as MyClass. You can use an extra inner class leading underscore.

Functions & Methods: Function names should be lowercase, you can use the underline style word to increase readability. Such as: myfunction, my_example_function.

* * Note: mixed case is allowed only for time already take advantage of this style, in order to maintain backward compatibility.

Function parameters and methods: always use "self" as an example of the method of the first parameter. Always use "cls" class method as the first parameter.

If the parameter name of a function and retention of key conflict, usually a good underscore suffix to use abbreviations or strange spelling.

Global variables: for from M import * import statements, if you want to stop global variable import module can use the old standard, plus a leading underscore in the global variables.

* * Note: Avoid using global variables

Variables: variable name all lower case, underlined by the connection of each word. The color = WHITE, this_is_a_variable = 1

* * Note: Whether a class member variable or global variable, m or g prefix not used.

2. The private class members to use a single underscore prefix to identify, define and more public members, less-defined private members.

3. The variable name with the type of information should not be, because Python is dynamically typed language. As iValue, names_list, dict_obj, etc. are bad name.

Constants: constant names all uppercase letters, each connected by underlining words such as MAX_OVERFLOW, TOTAL.

Exception: with "Error" as a suffix.

Abbreviations: full name should try to use the word spelling, abbreviations of the following two circumstances:

1. Common abbreviations, such as XML, ID, etc., when naming should be only the first letter capitalized, such as XmlParser.

2. Name contains long words on a word abbreviations. At this convention ChengSu abbreviations should be used.

For example: function abbreviated as fn

text abbreviated txt

abbreviated as object obj

count abbreviated cnt

abbreviated number num, and so on.

Leading underscore suffix

A leading underscore: that non-public.

A suffix underlined: avoid keyword conflicts.

Two leading underscores: Used when naming a class attribute name cause conflict.

Two leading and trailing underscore: "Magic" (Fig special) or an object property, e.g. __init__ or __file__. Never create such a name, but only to use them.

* * Note: There is some controversy about the use of an underscore.

Specific naming

__Xxx__ mainly refers to the form of reserved words nomenclature system. The project can also use this name, its significance lies in this form of the variable is read-only, this form of class member functions so as not to overload. Such as

class Base(object):

def __init__(self, id, parent = None):

self.__id__ = id

self.__parent__ = parent

def __message__(self, msgid):

# …slightly

Wherein __id __, __ parent__ and __message__ have adopted nomenclature system reservation word.

Attached: Google Python naming conventions

module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name.

There are several comments in Python?

These issues are fundamental programming language problems when it came must be complete and accurate answer, give the interviewer a good impression

1, single-line comments

In the front or in front of the code to be annotated content with '#', aims to clarify roles and explain a line of code, the code may not be a person in writing, but in the case of cooperative multiplayer, you have to ensure that people can own code soon understanding, but also to ensure their own after a period of time (in the case forgotten) can quickly think of the meaning of a line of code

2, multi-line comments

There are two multi-line comments, "" "" "" and '' '' '', but note that the same quotes do not appear like the same type of quotation marks.

3, coding comments

# - * - coding: UTF-8 - * - often appear at the top of the code, the code used for encoding label, common in python2 ', after python3 default encoding is utf-8, you do not need to add this line comments the

4. Notes platform

If you need to make Python programs run on the Windows platform, to be at the top of Python file with the #! / Usr / bin / python explanatory notes.

In addition, the comment is a method to develop good coding practices essential to have in their favor is more convenient for everyone, we hope, a reasonable standard to use in future programming.

How elegant a function to add a comment?

You can use docstring with type annotations

How to add a comment to the variable?

Python code indent support the Tab key and spaces mix.

not support

Can I import multiple libraries in an import in?

Yes, but not recommended, for reasons of ease of operation, regardless of the code itself:

Easier to read: import fred than import barney, betty, wilma, fred, bambam, pebbles easier to find.

Easier to search: by keyword search to immediately import fred position, while import barney, fred not.

Easier to edit: faster insertion and removal;

Easier to maintain: Once the module has been modified, to know the number of rows which module is being given wrong, and import line will be very troublesome;

If you miss or add a module, you can perceive through the number of rows and change position.

Summary: multi-line import more for the convenience of editing (copy, paste, delete), and maintain, and easy to search mentioned seem insignificant, because most people will be written at the beginning of Python import files, search the front of the file should be not difficult.

What needs to be noted in the file named Py time?

Try not to use the same file naming system

To name a few standardized tools Python style

PEP8

How to make the program more readable:

Suitably addition of non-leading spaces, blank lines, and a suitable consistent naming;

Guess you like

Origin www.cnblogs.com/qingaoaoo/p/12369966.html