File tree 1 file changed +15
-9
lines changed
1 file changed +15
-9
lines changed Original file line number Diff line number Diff line change @@ -737,18 +737,24 @@ Odds and Ends
737
737
=============
738
738
739
739
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 ::
742
742
743
- class Employee:
744
- pass
743
+ from dataclasses import dataclasses
745
744
746
- john = Employee() # Create an empty employee record
745
+ @dataclass
746
+ class Employee:
747
+ name: str
748
+ dept: str
749
+ salary: int
747
750
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
752
758
753
759
A piece of Python code that expects a particular abstract data type can often be
754
760
passed a class that emulates the methods of that data type instead. For
You can’t perform that action at this time.
0 commit comments