Loading...

Python Dataclasses

A data class keeps the fields, and the setup is written for you. Guest holds two things: the word nora and the seat 12. You do not install a package and you do not create a folder. The line @dataclass sits on the class. You do not write init, and you do not write str. You still build the guest yourself, with Guest("nora", 12). The word is passed first, then the number, because that is the order of the fields. print(guest) writes both of them on one line. This guest does not sit inside another object, and Guest is not a child of another class.

a guest with two fields

python
from dataclasses import dataclass

@dataclass
class Guest:
    name: str
    seat: int

guest = Guest("nora", 12)
print(guest)

The screen shows one line: Guest(name='nora', seat=12). nora appears in quotes because it is the stored word. 12 does not, because it is a whole number, and there is no decimal point. print writes that line. guest.name is nora. guest.seat is 12. There is no second line. The word badge is not added, and blue is not written. You never typed str. The dataclass line is what puts the fields into the printed line. Without print, the screen would stay empty, because building the guest is not the same as writing it.

Leave the seat out and the program stops. Guest("nora") is not in this program. The name of that stop is TypeError, because the seat field has no value. None is not written, and the program does not go on. The lines name: str and seat: int are the fields themselves. They are not a second guest, and they do not create a folder. class Guest(Pen) is not on this page. That form would make a child class. A bag that holds a pen is not on this page either. Here you have one guest, and the two fields live on that guest.

The next page is finding a fault. This page only stores a name and a seat, then prints them.

One guest, two fields

The screen is Guest(name='nora', seat=12). The word is nora and the seat is 12. You do not write init. The next page is finding a fault.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
7
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top