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

第7章 使用其他语言开发Python扩展

当编写基于Python的应用程序时,你不仅限于使用Python语言。在第3章中,简要提到过一些工具,如Hy。它允许你使用其他语言(Lisp的方言)编写模块,包,甚至整个应用程序,它们可以在Python虚拟机中正常运行。虽然它使你能够用完全不同的语法表达程序逻辑,但是它仍然是完全相同的语言,因为它最终被编译成相同的字节码。这意味着它具有与普通Python代码相同的限制。

  • 由于GIL的存在,线程可用性大大降低。
  • 它不编译。
  • 它不提供静态类型和相关的优化。

扩展,使用完全不同的语言进行编写,并通过Python扩展API公开其接口,这种解决方案有助于克服上述核心限制。

本章将讨论用其他语言编写自己的扩展的主要原因,并介绍有助于创建它们的流行工具。你将会学习到以下内容。

  • 如何使用Python/C API在C中编写简单的扩展。
  • 如何使用Cython编写扩展。
  • 扩展引入的主要挑战和问题是什么。
  • 如何在不创建专用扩展并且仅使用Python代码的情况下与编译的动态库交互。

当我们谈论使用不同语言的扩展时,我们几乎主要考虑C和C++。即使像Cython或Pyrex这样的工具,它们仅仅出于扩展的目的而提供了Python语言的超集,实际上它们只是源到源编译器,这种编译器可以使用扩展的类Python语法生成C代码。

当然,你可以在Python中使用任何语言编写的动态/共享库,只要可以这样编译,所以除了C和C++还是有别的方式。但共享库本质上是通用的。它们可以用于任何支持其加载的语言。因此,即使你使用完全不同的语言(例如说Delphi或Prolog)编写这样的库,如果不使用Python/C API,这样的库难以称之为Python扩展。 ...

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