Skip to Content
Python高级编程(第2版)
book

Python高级编程(第2版)

by Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
February 2024
Intermediate to advanced
423 pages
6h 9m
Chinese
Packt Publishing
Content preview from Python高级编程(第2版)

第4章 选择好的名称

大部分标准库在构建时都要考虑可用性。例如,内置类型的使用是很自然的,其设计非常易于使用。在这种情况下,Python可以与你开发程序时所思考的伪代码进行比较。大部分代码都可以大声朗读出来。例如,任何人都可以理解下面这个代码片段:

   my_list = []

   if 'd' not in my_list:
       my_list.append('d')

这就是编写Python比编写其他语言更加简单的原因之一。在编写程序时,你的思路可以快速转换成代码。

本章重点介绍编写易于理解和使用的代码的最佳实践,包括:

  • 使用PEP 8描述的命名约定。
  • 一组命名最佳实践。
  • 常用工具的简要介绍,这些工具可以让你检查是否遵守风格指南。

PEP 8为编写Python代码提供了一个风格指南。除了空格缩进、每行最大长度以及其他与代码布局有关的细节等基本规则之外,PEP 8还介绍了大部分代码库所遵循的命名约定。

本节给出了这一PEP的简要总结,并进一步给出了每种元素的命名最佳实践指南。但你仍然必须阅读PEP 8文档。

如果你正在创建一个打算开源的新软件包,那么答案很简单:始终遵守。PEP 8实际上是大多数Python开源软件的标准代码风格。如果你想接受来自其他程序员的任何协作,即使你对最佳代码风格指南有不同的看法,那么也应该坚持遵守PEP 8。这样做的好处是,其他程序员可以更容易地直接上手你的项目。对于新人来说,代码更容易阅读,因为它的风格与大多数其他Python开源包一致。

此外,开始时完全遵守PEP 8,可以让你在未来省时省事。如果你想向公众发布你的代码,最终其他程序员也会建议你切换到PEP 8。关于对某一特定项目是否真有必要这么做的争吵,可能会变成一场永无止境并且永远没有赢家的口水战(flame ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Hadoop实际解决方案手册

Hadoop实际解决方案手册

Posts & Telecom Press, JONATHAN OWENS, Lentz Jon, Femiano Brian
TensorFlow机器学习

TensorFlow机器学习

Posts & Telecom Press, Quan Hua, Shams Ul Azeem, Saif Ahmed
Python和NLTK实现自然语言处理

Python和NLTK实现自然语言处理

Posts & Telecom Press, Nitin Hardeniya
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835887745