search
HomeBackend DevelopmentPython TutorialPython programming specifications

Python programming specifications

Nov 22, 2016 pm 04:35 PM
python

Appropriate blank lines are helpful to increase the readability of the code. You can refer to the following guidelines for adding blank lines:

1) Add blank lines between the definitions of classes and functions;

2) Between import modules of different types Add blank lines;

3) Add blank lines between logical paragraphs in the function, that is, write related codes compactly together as a logical paragraph, with blank lines separating paragraphs;

> Line breaks

Although now Widescreen monitors can already display more than 256 columns of characters on a single screen, but this specification still adheres to the standard that the maximum line length should not exceed 80 characters. There are several ways to fold long lines:

1) Change the long variable name to a short name, such as:

this.is.a.very.long.variable_name = this.is.another.long.variable_name

It 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 wrap parentheses, square brackets and curly brackets The rows are implicitly concatenated, you can take advantage of this feature. If necessary, you can add an extra pair of parentheses around the expression

3) Add a line continuation character to a long line to force a line break. The position of the line break should be before the operator, and there should be an extra indent after the line break to facilitate maintenance When people look at the code, they can tell that there is a line break when they see the beginning of the line of code, such as:

if color == WHITE or color == BLACK \
    or color == BLUE: # 注意 or 操作符在新行的行首而不是旧行的行尾
do_something(color);

> String

1) Avoid using + and += operators in loops to accumulate strings. Since strings are immutable, doing so creates unnecessary temporary objects and results in quadratic rather than linear runtime. As an alternative, you can add each substring to a list and then use .join to join the lists after the loop ends. (You can also write each substring to a cStringIO.StringIO cache)

2) Use triple double quotes instead of triple single quotes for multi-line strings. Note, however, that it is often cleaner to use implicit line concatenation because multiline strings are inconsistent with the indentation of other parts of the program.

> Naming

Consistent naming can reduce a lot of trouble for developers, and appropriate naming can greatly improve the readability of the code and reduce maintenance costs.

>> Constants

Constant names are all capital letters, with underscores connecting each word, such as

WHITE = 0XFFFFFF
THIS_IS_A_CONSTANT = 1

>> Variables

Variable names are all lowercase, with underscores connecting each word, such as

color = WHITE
this_is_a_variable = 1

Private class members Use a single underscore prefix to identify more public members and less private members.

Variable names should not carry type information because Python is a dynamically typed language. Such as iValue, names_list, dict_obj, etc. are all bad names.

>> Function

The naming rules of function names are the same as variable names.

>> Classes

Use words starting with capital letters (such as CapWords, Pascal style) for class names, and do not use underscores to connect words. For example:

class ThisIsAClass(object):pass

>> Module

Module names are all lowercase. For modules used in packages, you can add an underscore prefix, such as

module.py_
internal_module.py

>> Package

The naming convention of packages is the same as that of modules.

>> Abbreviations

should try to use fully spelled words when naming. There are two types of abbreviations:

1) Commonly used abbreviations, such as XML, ID, etc., should only capitalize the first letter when naming. Such as

class XmlParser(object):pass

2) If the name contains long words, abbreviate a certain word. At this time, it should be used as an agreed abbreviation method, such as removing vowels, the first character containing consonants, etc. For example:

Function is abbreviated as FN

Text abbreviated as TXT

Object

Number is abbreviated as num, etc.

>> The specific naming method

mainly refers to the system reserved word naming method in the form of __xxx__. This kind of naming can also be used in projects. Its significance is that variables in this form are read-only, and class member functions in this form should not be overloaded as much as possible. Such as

class Base(object):
    def __init__(self, id, parent =None):
        self.__id__ = id
        self.__parent__ = parent    def __message__(self, msgid):
        # …略

where __id__, __parent__ and __message__ all use system reserved word nomenclature.

>> Import format

1) The order of import, first import Python built-in modules, then import third-party modules, and finally import other modules in self-developed projects; these modules are separated by blank lines .

2) Each import should be on its own line.

3) Do not use from module import * unless it is an import constant definition module or other module where you ensure that there will be no namespace conflicts.

> Assignment

For assignment languages, the main thing is not to do unnecessary alignment, such as

a            = 1                               # 这是一个行注释
variable = 2                               # 另一个行注释
fn           = callback_function    # 还是行注释

没有必要做这种对齐,原因有两点:一是这种对齐会打乱编程时的注意力,大脑要同时处理两件事(编程和对齐);二是以后阅读和维护都很困难,因为人眼的横向视野很窄,把三个字段看成一行很困难,而且维护时要增加一个更长的变量名也会破坏对齐。直接这样写为佳:

a = 1 # 这是一个行注释
variable = 2 # 另一个行注释
fn = callback_function # 还是行注释

>  语句

通常每个语句应该独占一行。不过, 如果测试结果与测试语句在一行放得下, 你也可以将它们放在同一行。如果是if语句, 只有在没有else时才能这样做。特别地,绝不要对 try/except 这样做,因为try和except不能放在同一行。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!