Dataclasses
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
A class that only holds data still needs __init__, __repr__ and __eq__, and writing them by hand is dull and easy to get wrong. The @dataclass decorator reads the class's annotated fields and writes those methods for you. Step through an eight-line program, point.py: watch the decorator fill the class's method slots, build a Point with a default, print it and compare it, then meet the one rule that stops it: no mutable defaults.
5 أسئلة سريعة
اختر إجابة لتعرف السبب. تُحفَظ نتيجتك مع تقدّمك.
01Which of these lines inside a @dataclass class creates a field?
A field is a class variable with a type annotation, name: type. count = 0 without an annotation is a plain class attribute, and @dataclass ignores it.
02@dataclass class Pair: a: int b: int = 5 What does print(Pair(1)) show?
The generated __init__ gives b its default 5, and the generated __repr__ writes the class name and each field as name=value.
03Two dataclass objects are made separately: Point(1, 2) and Point(1, 2). What does == give?
The generated __eq__ compares the fields in order, like tuples. A plain class without __eq__ would give False, since it compares identity.
04@dataclass class Pair: a: int What does Pair("hi") do?
Type annotations are hints for people and tools such as type checkers. Python does not check them when the program runs.
05Which field gives every new object its own empty list?
default_factory is called for each new object. A plain [] (or list()) default would be one list shared by every object, so @dataclass refuses it with a ValueError.
المسرد
- Dataclass
- A class made with the @dataclass decorator, which writes __init__, __repr__ and __eq__ from its fields.
- Decorator
- A function that takes a function or class and returns it changed. @name above a definition applies it: C = name(C).
- Field
- A class variable with a type annotation, such as x: int, inside a dataclass. Fields are kept in the order they are written.
- Type annotation
- A hint after a colon, as in x: int, saying what type a value should be. Python does not check it at run time.
- Boilerplate
- Repetitive code that must be written but says little, such as an __init__ that only copies its arguments.
- __repr__
- The special method that gives an object's text form for developers; print() uses it when there is no __str__.
- __eq__
- The special method behind ==. A dataclass's version compares the fields in order.
- default_factory
- An argument to field(): a function called to make a fresh default, such as list, for each new object.
الملاحظات والمصادر
- On macOS and Linux the command is often python3 rather than python; on Windows the py launcher also works. The $ is the terminal's own prompt: you do not type it.
- @dataclass also takes options: @dataclass(frozen=True) makes the fields read-only, order=True adds <, <=, > and >=, and slots=True (Python 3.10+) uses __slots__. The defaults are init=True, repr=True and eq=True.
- Because eq=True and frozen=False, @dataclass also sets __hash__ to None, so a Point cannot go in a set or be a dict key; frozen=True makes it hashable.
- A field without a default cannot come after a field with one, just as in a def. The real traceback lists the lines inside dataclasses.py; the figure shortens them to ..., and wraps the last line to fit the terminal.
- Since Python 3.11 the check refuses any unhashable default (such as a list, dict or set), not only those three types.
- Python library: dataclasses — Data Classes
- Python library: dataclasses — Mutable default values
- PEP 557 — Data Classes
- Python reference: Class definitions (decorators)
- Python reference: Data model — basic customization (__init__, __repr__, __str__, __eq__)
- Python glossary: decorator, annotation
- Python library: Built-in functions (print)
- Python tutorial: Classes
اختبار يتاح بعد الخطوة الأخيرة.