Records

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
#
from dataclasses import dataclass
#
@dataclass
class Book:
    title: str = ""
    year : int = 0
    cost : float = 0.0
    outofPrint : bool = False
#

Creating New Records

Method 1

#
newBook = Book()
newBook.title= "XYZ"
newBook.year = 2001
newBook.price = 14.99
newBook.outOfPrint = False
#

Method 2

#
newBook = Book("XYZ", 2001, 14.99, False)
#