mirror of
https://github.com/python/cpython.git
synced 2025-09-27 18:59:43 +00:00
gh-99908: Tutorial: Modernize the 'data-record class' example (#100499)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
This commit is contained in:
parent
c6dac12861
commit
00afa5066b
1 changed files with 15 additions and 9 deletions
|
@ -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
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue