Reading preferences
Concept

Properties, Dataclasses, and Abstract Classes

Model validated state, generated methods, and explicit class contracts.

python, properties, dataclasses, abstract classes

An attribute can enforce a rule

A property offers attribute syntax backed by methods. A dataclass generates common methods from declared fields. An abstract base class (ABC) can declare operations that concrete subclasses must implement.

Python illustration

from dataclasses import dataclass, field

@dataclass
class ReadingList:
    titles: list[str] = field(default_factory=list)

    @property
    def count(self):
        return len(self.titles)

first = ReadingList()
second = ReadingList()
first.titles.append("Patterns")
print(first.count, second.count)

Prepared output — not live execution:

1 0

The factory makes a separate list for each instance. The read-only count property calculates a value from the list when accessed; it is not a stored counter that must be updated separately.

See the reasoning

Compare two instances

See how a default factory separates the lists and a property reads them. This is a prepared demonstration, not live code execution.

Construct both instances

Instance state
  1. first.titles[]Current focus
  2. second.titlesa different []
  3. count propertyreads list length

The factory makes a fresh list for each instance.

Setters and contracts

A property setter can validate a proposed value before storing it, but a leading underscore is still a convention, not a security boundary. Dataclasses do not validate field types automatically; type annotations are not runtime enforcement. frozen=True blocks ordinary attribute assignment but does not recursively freeze mutable contained objects.

Derive from abc.ABC and mark required methods with @abstractmethod to express a nominal contract. An incomplete subclass remains abstract. An ABC checks that required methods are implemented, not that they behave correctly. See protocols for structural, rather than explicit, contracts.

from abc import ABC, abstractmethod

class Formatter(ABC):
    @abstractmethod
    def format(self, text):
        pass

class UpperFormatter(Formatter):
    def format(self, text):
        return text.upper()

print(UpperFormatter().format("read"))

The prepared output is READ. Instantiating Formatter() directly raises TypeError because its abstract method has not been implemented.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What can a property provide?
2. What can dataclass generate by default?
3. How can a dataclass create a separate list for each instance?
4. Can an ABC with an unimplemented abstract method normally be instantiated?

References and further reading