Python coding standards and code optimization

Blogger: Light of Destiny

Column: Python Programming

Python coding conventions

Python programs are composed of packages, modules (i.e. a Python file), functions, classes and statements

(1) Naming rules

Variable names, package names, and module names usually start with a lowercase letter . If the name contains multiple words, the first word is generally lowercase and the first letter of each subsequent word is capitalized. Camel case notation, such as myBook. Can also be in all lowercase format separated by underscore_, such as student_name.

It is recommended to use all uppercase letters for constants, such as PI.

The first letter of the class name is capitalized, and multiple words are expressed in camel case, such as BookInfo.

Function names generally use lowercase letters, and multiple words use camel case notation. getName(); get_name()

(2) Code indentation

Use the Tab key and spaces to indent code, but do not mix Tabs and spaces to indent. The indentation in Python represents the scope of the program block. If the wrong code indentation is used, the program will throw an exception.

(3) Space/blank line

Use blank lines to separate functions or statement blocks to separate two code blocks with different functions and enhance readability. It is recommended to use spaces to separate both sides of the operator, and do not add spaces on both sides of the function parameter assignment statement.

(4) Comment---#Single-line comment, """ Multi-line comment"""

Comments are helpful for understanding the program and team development. Functions and classes must be added with functional and usable comments, and complex algorithms must be properly commented.

(5) Each import statement only imports one module, and try to avoid importing multiple modules at once.

(6) If a line of statements is too long, you can use the line continuation character "\" at the end of the line to continue writing code on the next line.

(7) Appropriate use of exception handling structures to improve the fault tolerance and robustness of the program.

import string
class Stack():
	def__init__(self,  size=10):
		self.__content = []              #定义列表存放栈的元素
		self.__size = size                #初始化栈的大小
			self.__current = 0               #栈中元素个数初始化为0
# 将堆栈清空
	def empty(self):
		self.__content = []
		self.__current = 0
# 判断堆栈是否为空
	def isEmpty(self):
		if not self.__content:
			return True
		else:
			return False

Guess you like

Origin blog.csdn.net/VLOKL/article/details/133417915