current position：Home>The basic grammar of python learning---ideological understanding before grammar learning---programming thought and code specification (1) day5
The basic grammar of python learning---ideological understanding before grammar learning---programming thought and code specification (1) day5
PythonThe grammar and other language such asJava,PHPAnd so on basic is consistent with the,只是PythonThere may be some of the rules for themselves inside,因此,Python不仅是一门简单易学的编程语言,Is also a key to can quickly open other programming languages.
在任意的PythonWithin the terminal to write import this 将会看到Tim Peters写的Zen,其内容如下：
Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
The above content translation is as follows：
Beautiful beautiful code is better than ugly.That means we not only requires code works,And also hope the code looks beautiful. •Explicit is better than implicit.Is simply our code to specify its usage,Don't let the users according to their own understanding to guess. •简单优于复杂.Can use simple method must not deliberately looking for trouble,The simplest method is the best way to. •复杂胜于凌乱.If the function is very complex,Is hopes to split its success can be a single multiple modules;Want to keep the indirect mouth function module is simple,保证各个模块功能单一. •扁平优于嵌套.Just try not to use nested,After all nested code when debugging,Positioning problem more troublesome,Don't know where is a nested layer when the problem. •Loose is superior to the compact.The connection between the various code modules to simple,Can't rely too much on some modules,Don't be too complex and the connection between the different modules form the spider mesh. •代码可读性很重要.变量名、函数名、The meaning of the name of the class had better have clear.注释也是很重要的,Comments can help us and others to understand the code. •Even if is a special case,And do not violate the above rules.This so-called exception is some case,If we don't abide by the rules,Look at more cost-effective.But if our code is long service in our,So we abide by these rules will eventually benefit from. •Although the reality is often not so perfect,But should not pass any exception.Exception handling is very important,90%The problem occurs in the marginal cases. •Exception handling is careless.Although most of the anomaly probability is very low,但是我们不能掉以轻心,Hope to be able to find where the exception happened, in the reason and solve it,不能使用exceptCapture the exception and then whatever. •如果存在多种可能,不要猜测.There must be a,Is usually only a best solution. •Treat the code,要有精益求精的精神,逐步改进,Let it tend to be perfect. •虽然这并不容易,因为你不是Python之父.Fully implemented according to the above,The beginning may be a bit difficult,但是坚持下来,Things will get easier. •Hand is better than not to start work.Programming is not only the mental work,And manual labor.多多练习,Will pay the practice idea can help us better understand the advantages and disadvantages of code. •不假思索就动手还不如不做.动手之前,需要思考,确定目标,了解现状.比如,We want to complete the function of whether there is a similar library can be used,They can meet our needs,Even if can't completely meet the needs of our,But you can see what are the design thought is worth our using for reference. •如果你的方案很难懂,It must be a bad solution.A complicated scheme,Generally it is difficult to realize,After all the code still needs to write.If the code of people's understanding of this scheme is bad,Results and expectations,After all, aware that big difference. •如果你的方案很好懂,那肯定是一个好方案.If a solution is very easy to understand,When the project demonstration everyone can understand very well,Can also help to advise.在开发时,The developer also easy to guarantee the development progress and quality,Test plan and implementation are also much easier to.Finally come out a hot style is a big probability event,Everyone can benefit from it. •命名空间非常有用,我们应当多加利用.Try not to put too many things in one package,This will lead to the function is not clear,Like a grocery store.Should try to effectively organize will code according to some way.
Although there are so a rainbow fart,但这个ZenThe whole idea is right：
Although that way may not be obvious at first unless you're Dutch.
Above is also not onlyPythonLanguage can be used,其实,Other language can also be applied,总结来说,Code programming grace never out of date,简洁,易读,结构合理,变量定义,函数定义,The meaning of the class definition, and so on have a clear（Is really easy to read）,结构不要太复杂（Multilayer nested will increase the difficulty reading on the logic,Actually also is easy to read）,逻辑清晰,完整.
The above requirement is to the requirement of a good code farmers（Cultivate a good programming habits are long term,也是一个良好的开端,The start of the,那么,Things behind you should correct）.（有时候,I will be back to see some I write my own code,If I had to give a feeling,那么,我想说,There are some code as ugly as shit.哈哈）
PEP是Python Enhancement Proposal的缩写,通常翻译为“Python增强提案”.
#1、使用空格来表示缩进而不要用制表符（Tab）.这一点对习惯了其他编程语言的人来说简直觉得不可理喻,因为绝大多数的程序员都会用Tab来表示缩进,但是要知道Python并没有像C/C++或Java那样的用花括号来构造一个代码块的语法,在Python中分支和循环结构都使用缩进来表示哪些代码属于同一个级别,鉴于此Python代码对缩进以及缩进宽度的依赖比其他很多语言都强得多.在不同的编辑器中,Tab的宽度可能是2、4或8个字符,甚至是其他更离谱的值,用Tab来表示缩进对Python代码来说可能是一场灾难. #2、和语法相关的每一层缩进都用4个空格来表示. #3、每行的字符数不要超过79个字符,如果表达式因太长而占据了多行,除了首行之外的其余各行都应该在正常的缩进宽度上再加上4个空格. #4、函数和类的定义,代码前后都要用两个空行进行分隔. #5、在同一个类中,各个方法之间应该用一个空行进行分隔. #6、二元运算符的左右两侧应该保留一个空格,而且只要一个空格就好.
PEP 8Advocate use different naming style to namePythonDifferent identifiers in,So that can pass the name of the identifier when reading the code to determine the identifier inPython中扮演了怎样的角色（在这一点上,PythonIts own built-in modules and some third-party modules are doing is not good）.
#1、变量、函数和属性应该使用小写字母来拼写,如果有多个单词就使用下划线进行连接. #2、类中受保护的实例属性,应该以一个下划线开头. #3、类中私有的实例属性,应该以两个下划线开头. #4、类和异常的命名,应该每个单词首字母大写. #5、模块级别的常量,应该采用全大写字母,如果有多个单词就用下划线进行连接. #6、类的实例方法,应该把第一个参数命名为self以表示对象自身. #7、类的类方法,应该把第一个参数命名为cls以表示该类自身.
在Python之禅（可以使用import this查看）In such a famous saying：“There should be one-- and preferably only one --obvious way to do it.”,翻译成中文是“Do one thing should have and the best is only a kind of exact practice”,This sentence to convey ideas inPEP 8Is ubiquitous in.
#1、采用内联形式的否定词,而不要把否定词放在整个表达式的前面.例如if a is not b就比if not a is b更容易让人理解. #2、不要用检查长度的方式来判断字符串、列表等是否为None或者没有元素,应该用if not x这样的写法来检查它. #3、就算if分支、for循环、except异常捕获等中只有一行代码,也不要将代码和if、for、except等写在一起,分开写才会让代码更清晰. #4、import语句总是放在文件开头的地方. #5、引入模块的时候,from math import sqrt比import math更好. #6、如果有多个import语句,应该将其分为三部分,从上到下分别是Python标准模块、第三方模块和自定义模块
PEP8Is a loose standard,Does not require all people to enforce,Even if you don't according to the standard,Write out a project,OK,If the project can be run,No one will say you what.但,Do not have a unified code is not standard,It will produce in the subsequent code maintenance ways problem.比如,The following simple example
简单例子1,两数相加,If this is according to specification：
nm1 = 3 nm2 = 4 print("nm1 + nm2 = " , nm1+nm2)
If you want to write as ugly as shit,那么就这样：
nm1=3 nm2=4 print("nm1+nm2=",nm1+nm2)
The example here is an example of a space,可以看到,变量定义=According to the specification there should be a space after,printOptimization function also did the appropriate box,The output will be elegant,Rather than gather together into a pile of.
简单例子2 Many module reference order：
import array import os import sys
import os import sys from numpy import array
The wrong example where is wrong？虽然arrayThis library is can refer to success,也可以引用到,但,We don't know this library which is the parent of the,The subsequent code reading will give other people who do not know the situation caused problems,并且,PythonBuilt-in libraries should be in the front,The third party in the back,There is no custom modules,如果有,那么,The custom module should be written in the last, oh.
当然,Above are some simple examples illustratePEP8规范,The classmate can contrast the above specification carefully study and get a good code programming habits.
If a project unified code implementation standards,那么,For inherited classmate behind,这是一个好的开端,否则,将会是一场灾难.
author[zsk_john],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python's common modules of threading and Thread modules The first stage of thread implementation
- Blender Python Programming: Creating Emitting Materials
- Python multiprocessing
- How does python implement image edge detection
- Django paging method
- django regex
- How does Python represent time?2 modules, 3 ways, 1 text to understand~
- Modify column name and row index in pandas DataFrame
- [python pandas groupby]
- Python Daily Practice (New Question Bank of Niu Ke) - Day 20: Dictionary Practice
guess what you like
[LeetCode brush questions] Hash table - some questions are implemented with built-in functions (with Python code)
[LeetCode brush questions] Linked list topic (1) (with Python code)
[Small case of python learning] Simulation system invasion to enhance interest
Getting Started with Python Basics - Essential Knowledge for Getting Started
How does Python represent time?2 modules, 3 ways, 1 text to get it~
Python office software automation, master openpyxl operation in 5 minutes
Introduction to Python Basics - Variables, Strings
[python2] remove the u in front of the unicode string
How to use the Python Color class to draw text
How to use Asyncio Python web programming
- 27 Python artificial intelligence libraries have been sorted out, it is recommended to collect!
- [Python] Word2Vec predicts what will be left if I subtract 'love' from my 'life'
- When I export a pandas package, there is a problem. If I don't import it, there is no problem. Is this not enough memory?
- Python version 3.7.4 How can I install locust successfully?
- How does python use pyinstaller to package music into exe, that is, play background music when running the packaged program?
- Python use pyinstaller how to wrap up music exe, is to run a packaged program play background music?
- Rescue 007 of graph traversal application, detailed analysis of python version
- 27 Python artificial intelligence libraries have been sorted out, it is recommended to collect~
- pandas DataFrame data filtering (2)
- Python is how to represent time?- two modules, three ways, complete the ~ 1
- The definition of pycharm writing python code
- Problems defining functions in Python
- Python Socket Network Programming
- Django server running error
- Python image processing notes - image matching based on Harris corners (skimage)
- (Thirteen--1) Concurrent programming of python (thread, queue, process, coroutine, process thread coroutine comparison)
- (12) Python's memory management mechanism
- Python crawler entry case day07: Hippopx
- Django reports an error ModuleNotFoundError: No module named 'mysqlclient'
- Python study notes
- How to upgrade python? python3 version and install pip3
- [Python] 4-word summary for amateurs, PyCharm2022.2 Professional Edition improves development efficiency, basic settings and common shortcut keys (super practical) & basic knowledge of Python - CSDN 21-day learning challenge
- [Python Data Science Quick Start Series | 03] Playing with Data Extraction: Numpy Indexing and Slicing
- Python draws a curve experiment with matplotlib
- How to represent unequally spaced values with equally spaced values in Python?
- The principle of python decorator
- Python dictionary usage summary
- How to install python, configure environment variables, and change sources for third-party libraries
- [Conda] python data analysis/deep learning environment configuration windows+conda+jupyter+pytorch
- 【Conda】python environment setup , windows+conda+jupyter+pytorch (English Version)
- [Pandas] A primer on Pandas processing csv file datasets (neural network/machine learning algorithm data preprocessing)
- 100 days proficient in python (basic version) -- the first day: python and vscode environment installation
- How does python solve high concurrency
- Using the python library geopy method calculating the distance between the multiple sets of longitude and latitude
- python---SSH connection to linux service
- [reprint] Python - list comprehension
- Python Computer Vision Programming - Chapter 2 Local Image Descriptors
- "Compared to Excel, easy learning Python data analysis," reading notes -- -- -- -- -- - data operation
- Why is a function in the math module opened in python or in the IDE of pycharm, only the definition is not implemented?