Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
168
10
10.12
数据类
很多人创建对象主要是为了存储数据(作为对象特性),对行为(方法)并不是特别看重。
上一节刚刚介绍过的具名元组可以作为一种替代的数据存储方案。
Python 3.7
引入了
数据类
来看一个包含单个特性
name
的普通对象:
>> class TeenyClass():
... def __init__(self, name):
... self.name = name
...
>>> teeny = TeenyClass('itsy')
>>> teeny.name
'itsy'
实现同样效果的数据类看起来略有不同:
>>> from dataclasses import dataclass
>>> @dataclass
... class TeenyDataClass:
... name: str
...
>>> teeny = TeenyDataClass('bitsy')
>>> teeny.name
'bitsy'
除了需要
@dataclass
装饰器,定义类特性的时候要使用形如
name
:
type
name
:
type
=
val
变量注解
,比如
color: str
color: str = "red"
,其中,
type
可以是包括类在内的任
Python
对象类型,不仅限于内建类型(比如
str
int
)。
在创建数据类对象时,要按照类中指定的顺序提供参数,或是使用具名参数(可以采用任
意顺序):
>>> from dataclasses import dataclass ...
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.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223