]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-99908: Tutorial: Modernize the 'data-record class' example (GH-100499)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 24 Dec 2022 15:32:00 +0000 (07:32 -0800)
committerGitHub <noreply@github.com>
Sat, 24 Dec 2022 15:32:00 +0000 (07:32 -0800)
(cherry picked from commit 00afa5066bd45348ed82a38d3442763b2ed1a068)

Co-authored-by: JosephSBoyle <48555120+JosephSBoyle@users.noreply.github.com>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Doc/tutorial/classes.rst

index d7a24b4893fbb2601cb07537ad63d254c7f56202..5abb767cb0a8a8a7858bf3d2994d23240dd44b8d 100644 (file)
@@ -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