Skip to content

Commit

Permalink
gh-99908: Tutorial: Modernize the 'data-record class' example (GH-100499
Browse files Browse the repository at this point in the history
)

(cherry picked from commit 00afa50)

Co-authored-by: JosephSBoyle <48555120+JosephSBoyle@users.noreply.github.com>
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
  • Loading branch information
3 people committed Dec 24, 2022
1 parent ecfe468 commit 3ea6f7f
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions Doc/tutorial/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 3ea6f7f

Please sign in to comment.