Skip to content

Commit a7eee89

Browse files
miss-islingtonJosephSBoyleAlexWaygood
authored
gh-99908: Tutorial: Modernize the 'data-record class' example (GH-100499)
(cherry picked from commit 00afa50) Co-authored-by: JosephSBoyle <48555120+JosephSBoyle@users.noreply.github.com> Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
1 parent ba87dae commit a7eee89

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

Doc/tutorial/classes.rst

+15-9
Original file line numberDiff line numberDiff line change
@@ -737,18 +737,24 @@ Odds and Ends
737737
=============
738738

739739
Sometimes it is useful to have a data type similar to the Pascal "record" or C
740-
"struct", bundling together a few named data items. An empty class definition
741-
will do nicely::
740+
"struct", bundling together a few named data items. The idiomatic approach
741+
is to use :mod:`dataclasses` for this purpose::
742742

743-
class Employee:
744-
pass
743+
from dataclasses import dataclasses
745744

746-
john = Employee() # Create an empty employee record
745+
@dataclass
746+
class Employee:
747+
name: str
748+
dept: str
749+
salary: int
747750

748-
# Fill the fields of the record
749-
john.name = 'John Doe'
750-
john.dept = 'computer lab'
751-
john.salary = 1000
751+
::
752+
753+
>>> john = Employee('john', 'computer lab', 1000)
754+
>>> john.dept
755+
'computer lab'
756+
>>> john.salary
757+
1000
752758

753759
A piece of Python code that expects a particular abstract data type can often be
754760
passed a class that emulates the methods of that data type instead. For

0 commit comments

Comments
 (0)