Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第8章 使用类定义新类型

在Python中,若想使用内置的标量和集合类型,我们还有很长的路要走。对于许多问题,内置的类型以及Python标准库提供的内容是完全足够的。但有时候,它们并不能完全满足需求,此时就可以使用类来创建自定义类型。

正如我们所看到的,Python中的所有对象都有一个类型,而当使用type()内置函数来查看对象的类型时,输出的结果会显示对象的类型:

>>> type(5)
<class 'int'>
>>> type("python")
<class 'str'>
>>> type([1, 2, 3])
<class 'list'>
>>> type(x*x for x in [2, 4, 6])
<class 'generator'>

类用于定义一个或多个对象的结构和行为,每个对象被称为类的一个实例(instance)。总体来说,Python中的对象从创建或实例化直到被销毁,这段时间内对象都有固定的类型。将一个类看作一种用于构建新对象的模板或模式,这样想有助于理解类。对象的类可控制对象的初始化,并定义该对象具有哪些属性(attribute)和方法(method)。例如字符串对象,我们可以在该对象上使用定义在str类中的split()方法。

在Python中,类是面向对象编程(Object-Oriented Programming,OOP)的一个重要机制,虽然OOP有助于使复杂问题更易于处理,但它常常使得解决简单问题有些复杂。Python有一个很棒的优点,它高度支持面向对象,但是Python也不强制用户使用类,除非你真的需要它们。这使得Python与Java和C#完全不同。

类定义由class关键字引入,后跟类名。按照惯例,Python中的新类名称使用驼峰命名法(camel ...

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

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626