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版)

第2章 语法最佳实践——类级别以下

编写高效语法的能力会随着时间逐步提高。回头看看写的第一个程序,你可能就会同意这个观点。正确的语法看起来赏心悦目,而错误的语法则令人烦恼。

除了实现的算法与程序架构设计之外,还要特别注意的是,程序的写法也会严重影响它未来的发展。许多程序被丢弃并从头重写,就是因为难懂的语法、不清晰的API或不合常理的标准。

不过Python在最近几年里发生了很大变化。因此,如果你被邻居(一个爱嫉妒的人,来自本地Ruby开发者用户组)绑架了一段时间,并且远离新闻,那么你可能会对Python的新特性感到吃惊。从最早版本到目前的3.5版,这门语言已经做了许多改进,变得更加清晰、更加整洁、也更容易编写。Python基础知识并没有发生很大变化,但现在使用的工具更符合人们的使用习惯。

本章将介绍现在这门语言的语法中最重要的元素,以及它们的使用技巧,如下所示。

  • 列表推导(list comprehension)。
  • 迭代器(iterator)和生成器(generator)。
  • 描述符(descriptor)和属性(property)。
  • 装饰器(decorator)。
  • with和contextlib。

速度提升或内存使用的代码性能技巧将会在第11、12章中讲述。

Python提供了许多好用的数据类型,既包括数字类型,也包括集合类型。对于数字类型来说,语法并没有什么特别之处。当然,每种类型的定义会有些许差异,也有一些(可能)不太有名的运算符细节,但留给开发人员的选择并不多。对于集合类型和字符串来说,情况就发生变化了。虽然人们常说“做事的方法应该只有一种”,但留给Python开发人员的选择确实有很多。在初学者看来,有些代码模式看起来既直观又简单,可是有经验的程序员往往会认为它们不够Pythonic,因为它们要么效率低下,要么就是过于啰嗦。 ...

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