gh-99908: Tutorial: Modernize the 'data-record class' example (#100499)

Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
JosephSBoyle 2022-12-24 15:23:24 +00:00 committed by GitHub
parent c6dac12861
commit 00afa5066b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -738,18 +738,24 @@ Odds and Ends
============= =============
Sometimes it is useful to have a data type similar to the Pascal "record" or C 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 "struct", bundling together a few named data items. The idiomatic approach
will do nicely:: is to use :mod:`dataclasses` for this purpose::
from dataclasses import dataclasses
@dataclass
class Employee: class Employee:
pass name: str
dept: str
salary: int
john = Employee() # Create an empty employee record ::
# Fill the fields of the record >>> john = Employee('john', 'computer lab', 1000)
john.name = 'John Doe' >>> john.dept
john.dept = 'computer lab' 'computer lab'
john.salary = 1000 >>> john.salary
1000
A piece of Python code that expects a particular abstract data type can often be 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 passed a class that emulates the methods of that data type instead. For