diff options
author | Miss Islington (bot) <31488909+miss-islington@users.noreply.github.com> | 2022-12-24 15:32:00 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-12-24 15:32:00 (GMT) |
commit | a7eee898abb6314669d700e9a22013f2210b1b7e (patch) | |
tree | 86fb4c5466a2532c8e6d9a35ab354b67ff57ec91 /Doc/tutorial | |
parent | ba87dae4536bbc55db559950e0b8fa1201086586 (diff) | |
download | cpython-a7eee898abb6314669d700e9a22013f2210b1b7e.zip cpython-a7eee898abb6314669d700e9a22013f2210b1b7e.tar.gz cpython-a7eee898abb6314669d700e9a22013f2210b1b7e.tar.bz2 |
gh-99908: Tutorial: Modernize the 'data-record class' example (GH-100499)
(cherry picked from commit 00afa5066bd45348ed82a38d3442763b2ed1a068)
Co-authored-by: JosephSBoyle <48555120+JosephSBoyle@users.noreply.github.com>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Diffstat (limited to 'Doc/tutorial')
-rw-r--r-- | Doc/tutorial/classes.rst | 24 |
1 files changed, 15 insertions, 9 deletions
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst index d7a24b4..5abb767 100644 --- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -737,18 +737,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 |