Python dataclasses are very similar to records – a single object with several named attributes.
Note: dataclasses require Python 3.7+
Defining a Record
- Import commands should be at the very top of any program, followed by any constants.
- Dataclass definitions come next, before any subprograms.
- The @dataclass decorator is required before each dataclass definition, otherwise Python will try to use standard class definitions
- Names of dataclasses should start with a capital letter
01 02 03 04 05 06 07 08 09 10 | # from dataclasses import dataclass # @dataclass class Book: title: str = "" year : int = 0 cost : float = 0.0 outofPrint : bool = False # |
Creating New Records
Method 1
1 2 3 4 5 6 7 | # newBook = Book() newBook.title = "XYZ" newBook.year = 2001 newBook.price = 14.99 newBook.outOfPrint = False # |
Method 2
1 2 3 | # newBook = Book( "XYZ" , 2001 , 14.99 , False ) # |