summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJosephSBoyle <48555120+JosephSBoyle@users.noreply.github.com>2022-12-24 15:23:24 (GMT)
committerGitHub <noreply@github.com>2022-12-24 15:23:24 (GMT)
commit00afa5066bd45348ed82a38d3442763b2ed1a068 (patch)
treefbf483accc95f819ea8d99977ec9b5490b6b8878
parentc6dac128612df08fbd7f5e91dcd74a367bce0ed9 (diff)
downloadcpython-00afa5066bd45348ed82a38d3442763b2ed1a068.zip
cpython-00afa5066bd45348ed82a38d3442763b2ed1a068.tar.gz
cpython-00afa5066bd45348ed82a38d3442763b2ed1a068.tar.bz2
gh-99908: Tutorial: Modernize the 'data-record class' example (#100499)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
-rw-r--r--Doc/tutorial/classes.rst24
1 files changed, 15 insertions, 9 deletions
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
index 0e5a940..a206ba3 100644
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -738,18 +738,24 @@ Odds and Ends
=============
Sometimes it is useful to have a data type similar to the Pascal "record" or C
-"struct", bundling together a few named data items. An empty class definition
-will do nicely::
+"struct", bundling together a few named data items. The idiomatic approach
+is to use :mod:`dataclasses` for this purpose::
- class Employee:
- pass
+ from dataclasses import dataclasses
- john = Employee() # Create an empty employee record
+ @dataclass
+ class Employee:
+ name: str
+ dept: str
+ salary: int
- # Fill the fields of the record
- john.name = 'John Doe'
- john.dept = 'computer lab'
- john.salary = 1000
+::
+
+ >>> john = Employee('john', 'computer lab', 1000)
+ >>> john.dept
+ 'computer lab'
+ >>> john.salary
+ 1000
A piece of Python code that expects a particular abstract data type can often be
passed a class that emulates the methods of that data type instead. For