File tree Expand file tree Collapse file tree 1 file changed +15
-9
lines changed Expand file tree Collapse file tree 1 file changed +15
-9
lines changed Original file line number Diff line number Diff line change @@ -738,18 +738,24 @@ Odds and Ends
738738=============
739739
740740Sometimes it is useful to have a data type similar to the Pascal "record" or C
741- "struct", bundling together a few named data items. An empty class definition
742- will do nicely ::
741+ "struct", bundling together a few named data items. The idiomatic approach
742+ is to use :mod: ` dataclasses ` for this purpose ::
743743
744- class Employee:
745- pass
744+ from dataclasses import dataclasses
746745
747- john = Employee() # Create an empty employee record
746+ @dataclass
747+ class Employee:
748+ name: str
749+ dept: str
750+ salary: int
748751
749- # Fill the fields of the record
750- john.name = 'John Doe'
751- john.dept = 'computer lab'
752- john.salary = 1000
752+ ::
753+
754+ >>> john = Employee('john', 'computer lab', 1000)
755+ >>> john.dept
756+ 'computer lab'
757+ >>> john.salary
758+ 1000
753759
754760A piece of Python code that expects a particular abstract data type can often be
755761passed a class that emulates the methods of that data type instead. For
You can’t perform that action at this time.
0 commit comments