OOP with Classes
Classes become useful when several operations need the same state. Their design also determines whether two records compare equal, whether a node can enter a visited set, and whether an update affects another object.
Start with the class definition if this syntax is new. For a refresher, use shared state, identity and hashing, and the interview exercise. The examples use invented gene records, sample metadata, and graph nodes.
Choose an introductory or refresher route
Section titled “Choose an introductory or refresher route”For an introduction, work through class definitions, instances, shared state, validation, and dataclasses in page order. Run each example before you continue because later examples reuse the earlier definitions. Then inspect the AnnData example to connect objects with a familiar analysis container.
For an interview refresher, concentrate on shared state, copies, identity and hashing, and node cycles. Answer the practice questions before opening their explanations. The iterator lesson develops the iteration behavior used by the container example.
Two ways to organize code
Section titled “Two ways to organize code”Functions can accept separate values and return a result. Classes provide another way to organize the same work by keeping related attributes and methods on one object. These approaches can coexist in an analysis program.
Save the Python blocks in page order as oop_classes.py, then run
uv run python oop_classes.py from your project directory. The AnnData example
requires anndata, numpy, and pandas. The displayed results use Python 3.13,
AnnData 0.13.4, NumPy 2.5.4, and pandas 3.1.1. Add those libraries with
uv add anndata==0.13.4 numpy==2.5.4 pandas==3.1.1.
The earlier examples use only the standard library.
You can also download the complete Python script,
which includes the exercise checks.
# A function accepts one expression value.gene_name = "TP53"gene_chr = "chr17"gene_expr = 23.5
def is_expressed(expression: float, threshold: float = 1.0) -> bool: """Return whether expression exceeds a threshold.
Args: expression: Measured expression value. threshold: Minimum expressed value.
Returns: True when expression is above the threshold. """ return expression > threshold
print(is_expressed(gene_expr))TrueThe function needs only an expression value. A record containing a gene name, chromosome, and expression value becomes useful when several operations need those fields together.
In object-oriented programming, a class defines the attributes and methods of
its instances. Each Gene instance below stores one gene record. Its
is_expressed method reads the expression value from that instance.
Grouping fields does not validate their contents. A class can still contain an incorrect chromosome or expression value if its constructor accepts one.
You do not need to choose one style exclusively. Most bioinformatics code mixes both. Understanding classes helps you use libraries like scanpy, Biopython, and pandas, which are built with OOP.
Defining a class
Section titled “Defining a class”A class definition starts with the class keyword. Python normally creates
an instance through __new__, then initializes it through __init__.
These examples customize only initialization. The self parameter refers to
the instance whose method is running; it is a naming convention, not a keyword.
class Gene: """Represents a gene with expression data.
Attributes: name: The gene symbol. chromosome: The chromosome location. expression: The expression value. """
def __init__( self, name: str, chromosome: str, expression: float = 0.0 ) -> None: """Initializes a Gene instance.
Args: name: The gene symbol. chromosome: The chromosome location. expression: The expression value. Defaults to 0.0. """ self.name = name self.chromosome = chromosome self.expression = expression
def is_expressed(self, threshold: float = 1.0) -> bool: """Checks if the gene is expressed above a threshold.
Args: threshold: Minimum expression value. Defaults to 1.0.
Returns: True if expression exceeds the threshold. """ return self.expression > threshold
def __repr__(self) -> str: """Return the constructor-style representation of the gene.
Returns: A string containing the instance fields. """ return ( f"Gene(name={self.name!r}, chromosome={self.chromosome!r}, " f"expression={self.expression!r})" )
def __str__(self) -> str: """Return the gene label and expression value.
Returns: A short description of the gene record. """ return f"{self.name} ({self.chromosome}): {self.expression}"__init__initializes a newly created instance’s data.- An instance method receives the instance as its first argument, conventionally named
self. __repr__returns a developer-friendly string. It is shown when you inspect an object in the REPL.__str__returns a human-readable string. It is used byprint().
Using the class
Section titled “Using the class”Create an instance by calling the class like a function.
tp53 = Gene("TP53", "chr17", 23.5)print(tp53)TP53 (chr17): 23.5The repr() function calls __repr__, giving you the developer view.
print(repr(tp53))Gene(name='TP53', chromosome='chr17', expression=23.5)Access attributes directly with dot notation.
print(tp53.name)TP53Call methods the same way.
print(tp53.is_expressed())Trueprint(tp53.is_expressed(threshold=50.0))FalseWorking with multiple instances
Section titled “Working with multiple instances”Each instance holds its own data. You can store instances in a list and loop over them.
genes = [ Gene("TP53", "chr17", 23.5), Gene("BRCA1", "chr17", 45.2), Gene("EGFR", "chr7", 0.3),]
for gene in genes: status = "expressed" if gene.is_expressed() else "not expressed" print(f"{gene.name}: {status}")TP53: expressedBRCA1: expressedEGFR: not expressedInstance state and shared state
Section titled “Instance state and shared state”Assignment binds a name to an object. It does not copy that object. Two names
can therefore refer to one Gene, and a change through either name reaches
the same instance.
original_gene = Gene("MYC", "chr8", 2.0)gene_alias = original_geneseparate_gene = Gene("MYC", "chr8", 2.0)gene_alias.expression = 9.0print("Alias is original:", gene_alias is original_gene)print("Original expression:", original_gene.expression)print("Separate expression:", separate_gene.expression)print("Explicit method call:", Gene.is_expressed(original_gene))Alias is original: TrueOriginal expression: 9.0Separate expression: 2.0Explicit method call: Trueoriginal_gene.is_expressed() supplies original_gene as the first argument.
The explicit class call above shows that binding for this method. Reassigning
gene_alias to another object would change that name’s binding, without
changing original_gene.
A list on the class is shared
Section titled “A list on the class is shared”An attribute assigned in the class body belongs to the class. Instance lookup can find it there when the instance has no attribute with that name. This deliberately incorrect design puts every run’s events into one list.
class SharedRunLog: """Demonstrate an incorrectly shared event list.
Attributes: events: One mutable list shared by instances without an override. """ events: list[str] = []
first_log = SharedRunLog()second_log = SharedRunLog()first_log.events.append("align")print("Second run sees:", second_log.events)print("Same list:", first_log.events is second_log.events)second_log.events = ["count"]print("Class list after assignment:", SharedRunLog.events)print("Second instance after assignment:", second_log.events)Second run sees: ['align']Same list: TrueClass list after assignment: ['align']Second instance after assignment: ['count']The call to append changes the shared list. Assignment to second_log.events
creates an instance attribute that shadows the class attribute. These two
operations have different effects even though both use dot notation.
Create each run’s list during initialization instead. A shared string remains appropriate for the format name because every run uses the same format.
class RunLog: """Keep each run's events separate.
Attributes: format_name: Shared format label. events: Events belonging to this instance. """ format_name = "pipeline_log"
def __init__(self) -> None: """Create a new event list for this run.""" self.events: list[str] = []
run_one = RunLog()run_two = RunLog()run_one.events.append("align")print("First run:", run_one.events)print("Second run:", run_two.events)print("Same list:", run_one.events is run_two.events)print("Shared format:", run_one.format_name, run_two.format_name)First run: ['align']Second run: []Same list: FalseShared format: pipeline_log pipeline_logValidation and method types
Section titled “Validation and method types”A useful class preserves a rule about its state. For the next class, that rule
is a nonnegative Python integer read count. It explicitly rejects booleans,
which Python otherwise treats as a subclass of int.
The property validates both initialization and later assignment. Its setter checks the proposed value before replacing the stored count, so a rejected update leaves the previous value intact.
from typing import Self
class ReadBatch: """Store a sample label and a validated read count.
Attributes: sample_id: Sample label supplied by the caller. read_count: Nonnegative Python integer count; booleans are rejected. """
def __init__(self, sample_id: str, read_count: int) -> None: """Initialize a batch and validate its count.
Args: sample_id: Sample label; this example does not validate labels. read_count: Nonnegative Python integer count.
Raises: TypeError: If the count is not a Python int or is a bool. ValueError: If the count is negative. """ self.sample_id = sample_id self.read_count = read_count
@property def read_count(self) -> int: """Return the validated read count.
Returns: The stored nonnegative count. """ return self._read_count
@read_count.setter def read_count(self, value: int) -> None: """Replace the count after validation.
Args: value: Proposed count.
Raises: TypeError: If value is not a Python int or is a bool. ValueError: If value is negative. """ if type(value) is not int: raise TypeError("read_count must be a Python int, not bool") if value < 0: raise ValueError("read_count must be nonnegative") self._read_count = value
@classmethod def from_tsv(cls, line: str) -> Self: """Create a batch from a sample label and count separated by a tab.
Args: line: A string containing exactly two tab-separated fields.
Returns: A new instance of the class on which the method was called.
Raises: ValueError: If fields are missing, extra, or contain a bad count. """ sample_id, count_text = line.rstrip("\n").split("\t") return cls(sample_id, cls.parse_count(count_text))
@staticmethod def parse_count(text: str) -> int: """Parse an integer without accessing an instance or class.
Args: text: Integer text accepted by Python's int conversion.
Returns: The parsed integer; the property separately rejects negatives.
Raises: ValueError: If text cannot be parsed as an integer. """ return int(text)
batch = ReadBatch.from_tsv("S1\t120")batch.read_count = 150print("Batch:", batch.sample_id, batch.read_count)print("Parsed without an instance:", ReadBatch.parse_count("42"))for invalid_count in (-1, True, 2.5): try: batch.read_count = invalid_count except (TypeError, ValueError) as error: print(type(error).__name__, str(error))print("Count after rejected updates:", batch.read_count)Batch: S1 150Parsed without an instance: 42ValueError read_count must be nonnegativeTypeError read_count must be a Python int, not boolTypeError read_count must be a Python int, not boolCount after rejected updates: 150| Method form | Automatically supplied argument | Role in this example |
|---|---|---|
| Instance method or property | The instance, named self |
The property reads or changes one batch. |
| Class method | The class, named cls |
from_tsv constructs an instance through cls(...). |
| Static method | None | parse_count converts text without object state. |
Using cls(...) lets an inherited factory construct the subclass that receives
the call, provided its initializer accepts the same arguments. Self records
that return relationship for type checkers. A static method can also be a
module-level function; keep it on the class when that location helps callers
find a related operation.
The leading underscore in _read_count marks an internal attribute by
convention. It does not stop a caller from changing that attribute directly
and bypassing validation. Double underscores trigger name mangling to reduce
subclass name collisions; they do not provide access control.
Inheritance
Section titled “Inheritance”Inheritance lets a subclass reuse methods from a base class. The subclass can also add or override methods. Instance attributes exist after the relevant initialization code assigns them.
This example extends a gene record with results from one specified comparison. The caller supplies an adjusted p-value between zero and one and a finite log2 fold change. A real analysis with several comparisons would also need an identifier for each comparison.
import math
class DifferentialGene(Gene): """A gene with differential expression results.
Attributes: name: The gene symbol. chromosome: The chromosome location. expression: The expression value. log2fc: Finite log2 fold change. adjusted_pvalue: Finite adjusted p-value in the closed interval [0, 1]. """
def __init__( self, name: str, chromosome: str, expression: float, log2fc: float, adjusted_pvalue: float, ) -> None: """Initialize a gene record for one comparison.
Args: name: Gene symbol. chromosome: Chromosome label. expression: Expression value in the example's units. log2fc: Finite log2 fold change for the comparison. adjusted_pvalue: Finite adjusted p-value between zero and one.
Raises: TypeError: If result values are not numeric. ValueError: If an effect or adjusted p-value is invalid. """ super().__init__(name, chromosome, expression) self.log2fc = log2fc self.adjusted_pvalue = adjusted_pvalue self._validate_result()
def _validate_result(self) -> None: """Require finite results and an adjusted p-value in [0, 1].
Raises: TypeError: If result values are not numeric. ValueError: If an effect or adjusted p-value is invalid. """ if not math.isfinite(self.log2fc): raise ValueError("log2fc must be finite") if not math.isfinite(self.adjusted_pvalue): raise ValueError("adjusted_pvalue must be finite") if not 0 <= self.adjusted_pvalue <= 1: raise ValueError("adjusted_pvalue must be between zero and one")
def is_significant( self, alpha: float = 0.05, fc_threshold: float = 1.0 ) -> bool: """Apply adjusted p-value and effect-size thresholds.
Args: alpha: Finite cutoff in [0, 1], excluded from selection. fc_threshold: Finite nonnegative absolute effect cutoff, excluded.
Returns: True when both thresholds pass.
Raises: TypeError: If result values or cutoffs are not numeric. ValueError: If result values or cutoffs violate their bounds. """ self._validate_result() if not math.isfinite(alpha) or not 0 <= alpha <= 1: raise ValueError("alpha must be finite and between zero and one") if not math.isfinite(fc_threshold) or fc_threshold < 0: raise ValueError("fc_threshold must be finite and nonnegative") return ( self.adjusted_pvalue < alpha and abs(self.log2fc) > fc_threshold )
def direction(self) -> str: """Describe the sign of the estimated fold change.
Returns: "up", "down", or "unchanged" according to the estimate.
Raises: TypeError: If result values are not numeric. ValueError: If an effect or adjusted p-value is invalid. """ self._validate_result() if self.log2fc > 0: return "up" if self.log2fc < 0: return "down" return "unchanged"
def __repr__(self) -> str: """Return a representation containing the comparison result.
Returns: A string containing the gene and comparison fields. """ return ( f"DifferentialGene(name={self.name!r}, " f"chromosome={self.chromosome!r}, expression={self.expression!r}, " f"log2fc={self.log2fc!r}, " f"adjusted_pvalue={self.adjusted_pvalue!r})" )Here, super().__init__() reaches Gene.__init__ and sets the inherited fields.
In general, super() continues lookup after the current class in the instance
type’s method resolution order. It does not always mean a direct parent,
especially with multiple inheritance.
Because DifferentialGene inherits from Gene, it has access to all of Gene’s methods.
deg = DifferentialGene("TP53", "chr17", 23.5, 2.5, 0.001)print(deg)TP53 (chr17): 23.5The __str__ method was inherited from Gene, so print() uses that format. The is_expressed method is also inherited.
print(deg.is_expressed())TrueThe new methods work as expected.
print(deg.is_significant())Trueprint(deg.direction())updirection() reports the sign of the estimate even when the selection rule
does not pass. is_significant() applies the supplied thresholds; it does not
compute a statistical test or adjust p-values. See
Multiple Testing for that step.
The initializer and decision methods reject invalid comparison values.
The decision methods check again because these attributes remain mutable.
Otherwise, a NaN effect would fail both sign comparisons and incorrectly reach
the unchanged return. A negative adjusted p-value could also pass a cutoff
without representing a valid probability.
for effect, adjusted in ((float("nan"), 0.01), (1.5, -0.1)): try: DifferentialGene("TP53", "chr17", 23.5, effect, adjusted) except ValueError as error: print(type(error).__name__, str(error))ValueError log2fc must be finiteValueError adjusted_pvalue must be between zero and oneThe subclass overrides __repr__ but inherits __str__. The same repr()
operation therefore uses different implementations for the two objects.
This is polymorphism through a shared operation.
print("Lookup order:", [cls.__name__ for cls in DifferentialGene.__mro__])print("Is a Gene:", isinstance(deg, Gene))for record in (tp53, deg): print(repr(record))Lookup order: ['DifferentialGene', 'Gene', 'object']Is a Gene: TrueGene(name='TP53', chromosome='chr17', expression=23.5)DifferentialGene(name='TP53', chromosome='chr17', expression=23.5, log2fc=2.5, adjusted_pvalue=0.001)Dataclasses
Section titled “Dataclasses”Python’s dataclasses module reduces boilerplate. If your class is mainly a container for data, a dataclass generates __init__, __repr__, and __eq__ for you automatically.
from dataclasses import dataclass
@dataclassclass Sample: """Represents a sequencing sample.
Attributes: sample_id: Unique sample identifier. condition: Experimental condition. read_count: Total number of reads. passed_qc: Whether the sample passed quality control. """ sample_id: str condition: str read_count: int passed_qc: bool = TrueYou define the fields with type annotations. Default values go at the end, just like function arguments. No need to write __init__ yourself.
s1 = Sample("S1", "control", 25000000)print(s1)Sample(sample_id='S1', condition='control', read_count=25000000, passed_qc=True)Override defaults by passing the argument explicitly.
s2 = Sample("S2", "treated", 31000000, passed_qc=False)print(s2)print(s2.passed_qc)Sample(sample_id='S2', condition='treated', read_count=31000000, passed_qc=False)FalseDataclasses work well with list comprehensions and filtering.
samples = [ Sample("S1", "control", 25000000), Sample("S2", "control", 28000000), Sample("S3", "treated", 31000000), Sample("S4", "treated", 27000000, passed_qc=False),]
passed = [s for s in samples if s.passed_qc]print(f"Passed QC: {len(passed)}/{len(samples)}")Passed QC: 3/4Dataclasses are ordinary classes with selected methods generated for you. They can contain methods, properties, and validation. Choose them when their field-based initialization and comparison rules match your object. Use an ordinary class when you want to define those rules directly.
Independent defaults and initialization checks
Section titled “Independent defaults and initialization checks”The default_factory creates a fresh list when the caller omits notes.
Do not use notes=[] in an initializer signature because that default list
would be reused. Dataclasses reject an unhashable field default such as [];
the factory avoids that error and supplies separate lists.
__post_init__ runs after a generated initializer assigns the fields. It can
validate those fields or derive additional state. Type annotations alone do
not validate a value at runtime.
from dataclasses import field
@dataclassclass SampleNotes: """Keep notes for one sample with an initially valid label.
Attributes: sample_id: Nonempty string checked at initialization. notes: Mutable note list; each omitted default creates a new list. """ sample_id: str notes: list[str] = field(default_factory=list)
def __post_init__(self) -> None: """Validate the initial sample label.
Raises: TypeError: If the label is not a string. ValueError: If the label is empty or whitespace only. """ if not isinstance(self.sample_id, str): raise TypeError("sample_id must be a string") if not self.sample_id.strip(): raise ValueError("sample_id must not be blank")
def note_count(self) -> int: """Count this sample's notes.
Returns: Number of stored notes. """ return len(self.notes)
notes_one = SampleNotes("S1")notes_two = SampleNotes("S2")notes_one.notes.append("adapter content reviewed")print("Note counts:", notes_one.note_count(), notes_two.note_count())print("Same default list:", notes_one.notes is notes_two.notes)for invalid_label in (" ", 7): try: SampleNotes(invalid_label) except (TypeError, ValueError) as error: print(type(error).__name__, str(error))Note counts: 1 0Same default list: FalseValueError sample_id must not be blankTypeError sample_id must be a stringThe label check runs at initialization only. A later assignment to sample_id
does not call __post_init__ again. Use a property such as ReadBatch.read_count
when later assignments must satisfy the same rule. The notes annotation also
does not check each item appended to the list.
Assignment and copies preserve different references
Section titled “Assignment and copies preserve different references”A factory controls an omitted default. It does not copy a list that the caller explicitly supplies. A shallow copy creates another outer object while retaining references to its nested objects; a deep copy recursively copies this example’s nested list as well.
from copy import copy, deepcopy
shared_notes = ["received"]supplied_one = SampleNotes("S3", shared_notes)supplied_two = SampleNotes("S4", shared_notes)shallow_notes = copy(supplied_one)deep_notes = deepcopy(supplied_one)supplied_one.notes.append("reviewed")print("Explicit list shared:", supplied_one.notes is supplied_two.notes)print("Shallow outer object differs:", shallow_notes is not supplied_one)print("Shallow list:", shallow_notes.notes)print("Deep list:", deep_notes.notes)Explicit list shared: TrueShallow outer object differs: TrueShallow list: ['received', 'reviewed']Deep list: ['received']Choose which objects should be shared before you copy a scientific dataset. A deep copy of a large array can allocate substantial additional memory, and external resources do not necessarily support deep copying.
Identity, equality, and hashing
Section titled “Identity, equality, and hashing”Identity asks whether two references point to the same object. Equality asks
whether the object’s comparison rule considers the values equal. The plain
Gene class inherits identity-based equality from object. The default
Sample dataclass compares the fields of instances with the same concrete type.
gene_left = Gene("TP53", "chr17", 23.5)gene_right = Gene("TP53", "chr17", 23.5)sample_left = Sample("S1", "control", 120)sample_right = Sample("S1", "control", 120)print("Separate Gene objects compare equal:", gene_left == gene_right)print("Separate Sample objects compare equal:", sample_left == sample_right)print("Samples are the same object:", sample_left is sample_right)sample_right.read_count = 121print("Samples compare equal after change:", sample_left == sample_right)try: {sample_left}except TypeError as error: print(type(error).__name__, str(error))Separate Gene objects compare equal: FalseSeparate Sample objects compare equal: TrueSamples are the same object: FalseSamples compare equal after change: FalseTypeError unhashable type: 'Sample'A set element or dictionary key must be hashable. Equal objects must have equal hashes, and a key’s hash must remain stable while it is stored. Hash collisions are permitted; equal hashes alone do not establish equality.
The default mutable dataclass has eq=True and frozen=False, so dataclasses
set __hash__ to None. That is why this Sample cannot enter a set. Defining
__eq__ on an ordinary class also disables inherited hashing unless a suitable
__hash__ is supplied. unsafe_hash=True does not make mutable keys safe.
For a key that represents a sample within a study, use only stable fields.
Here both fields are strings, and frozen=True prevents ordinary assignment
to them. The generated value equality and hash then agree.
from dataclasses import FrozenInstanceError
@dataclass(frozen=True)class SampleKey: """Identify a sample within a study using immutable string fields.
Attributes: study_id: Study identifier supplied as a string. sample_id: Sample identifier supplied as a string. """ study_id: str sample_id: str
key_one = SampleKey("study_a", "S1")key_two = SampleKey("study_a", "S1")read_counts = {key_one: 120}print("Lookup through equal key:", read_counts[key_two])print("Number of distinct keys:", len({key_one, key_two}))try: key_one.sample_id = "S2"except FrozenInstanceError as error: print(type(error).__name__, str(error))Lookup through equal key: 120Number of distinct keys: 1FrozenInstanceError cannot assign to field 'sample_id'Freezing a dataclass does not recursively freeze its contents. A contained list can still change, and a generated hash cannot hash that list. Keep hash-relevant fields immutable and validate their types when external data supplies them.
Composition and container behavior
Section titled “Composition and container behavior”Inheritance promises that a subclass can be used where the base class is expected. Composition stores a related object as a field. A gene can have results from several comparisons, so a result containing a gene and a comparison identifier expresses that relationship more directly than adding every result to one gene instance.
@dataclassclass ComparisonResult: """Associate one gene with one named comparison.
Attributes: gene: Referenced gene object, which remains shared. contrast: Identifier for the comparison. log2fc: Estimated log2 fold change for that comparison. """ gene: Gene contrast: str log2fc: float
comparison_results = [ ComparisonResult(tp53, "treated_vs_control", 2.5), ComparisonResult(tp53, "recovery_vs_control", -0.4),]for result in comparison_results: print(result.gene.name, result.contrast, result.log2fc)print("Shared gene:", comparison_results[0].gene is comparison_results[1].gene)TP53 treated_vs_control 2.5TP53 recovery_vs_control -0.4Shared gene: TrueThese results share a Gene reference. If you need a historical snapshot,
store the relevant immutable identifiers or copy the required state explicitly.
For a table with many gene comparisons, a DataFrame may be a better representation
than one Python object per row.
Support Python operations through special methods
Section titled “Support Python operations through special methods”A collection class can contain sample records and support len() and iteration.
__len__ returns its size; __iter__ supplies a fresh iterator. Neither operation
requires inheritance from list.
from collections.abc import Iterable, Iterator
class SampleBatch: """Hold a separate outer collection of shared sample objects."""
def __init__(self, samples: Iterable[Sample]) -> None: """Copy the collection while retaining its sample references.
Args: samples: Sample objects to include in their supplied order. """ self._samples = list(samples)
def __len__(self) -> int: """Return the number of samples.
Returns: Size of the stored collection. """ return len(self._samples)
def __iter__(self) -> Iterator[Sample]: """Create an iterator over the stored samples.
Returns: A new iterator in collection order. """ return iter(self._samples)
def total_reads(records: Iterable[Sample]) -> int: """Sum read counts from any iterable of sample records.
Args: records: Sample objects whose counts are integers.
Returns: Sum of the supplied read counts. """ return sum(record.read_count for record in records)
collection = SampleBatch(samples)print("Collection length:", len(collection))print("Sample identifiers:", [sample.sample_id for sample in collection])print("List total:", total_reads(samples))print("Collection total:", total_reads(collection))Collection length: 4Sample identifiers: ['S1', 'S2', 'S3', 'S4']List total: 111000000Collection total: 111000000At runtime, total_reads needs iteration and objects with suitable read_count
attributes. This is duck typing: callers supply the operations the function
needs. The annotation is narrower; Iterable[Sample] asks a type checker for
Sample elements, while permitting different iterable containers. An iterable
of ReadBatch objects would work at runtime but would not satisfy that annotation.
Interview example: node identity and cycles
Section titled “Interview example: node identity and cycles”Two nodes can have the same value and still occupy different positions in a
graph or linked list. A visited set must distinguish those objects. With
eq=False, this dataclass inherits identity equality and identity-based hashing
from object; it does not compare node fields recursively.
@dataclass(eq=False)class Node: """Represent a mutable linked-list node with identity semantics.
Attributes: value: Stored integer value, which need not be unique. next: Following node, or None at the end of an acyclic list. """ value: int next: "Node | None" = None
def has_cycle(head: Node | None) -> bool: """Detect a repeated node identity during traversal.
Args: head: First node, or None for an empty list.
Returns: True if traversal reaches the same node object twice. """ visited: set[Node] = set() current = head while current is not None: if current in visited: return True visited.add(current) current = current.next return False
first_node = Node(7)second_node = Node(7)first_node.next = second_nodeprint("Same values:", first_node.value == second_node.value)print("Same node:", first_node is second_node)print("Distinct visited nodes:", len({first_node, second_node}))print("Repeated values form a cycle:", has_cycle(first_node))second_node.next = first_nodeprint("Link back forms a cycle:", has_cycle(first_node))visited_nodes = {first_node}first_node.value = 9print("Visited membership after value change:", first_node in visited_nodes)print("Empty list forms a cycle:", has_cycle(None))Same values: TrueSame node: FalseDistinct visited nodes: 2Repeated values form a cycle: FalseLink back forms a cycle: TrueVisited membership after value change: TrueEmpty list forms a cycle: FalseFor n distinct reachable nodes, this algorithm takes expected O(n) time and
O(n) auxiliary space. It adds each node once and stops at a repeated identity
or the end. A set of values would incorrectly call the first acyclic example
a cycle. Removing eq=False would make these default mutable dataclass nodes
unhashable.
The linked-list lesson covers pointer updates. Its cycle exercise asks for two moving references, which can reduce auxiliary space to O(1). The tree lesson uses the same distinction between a node and its stored value.
AnnData: OOP in practice
Section titled “AnnData: OOP in practice”AnnData stores a matrix together with observation and variable metadata. Its rows represent observations, and its columns represent variables. In this example, the observations are samples and the variables are genes. In a single-cell analysis, the observations usually represent cells.
The invented matrix below has three samples and two genes. Each matrix row
uses the same sample order as obs, and each column uses the gene order in
var. Supply that order correctly when you create the object.
import pandas as pdimport anndata as adimport numpy as np
counts = np.array([ [100, 250], [120, 300], [90, 280],])
adata = ad.AnnData( X=counts, obs=pd.DataFrame( {"condition": ["control", "treated", "treated"]}, index=["Sample1", "Sample2", "Sample3"], ), var=pd.DataFrame(index=["TP53", "BRCA1"]),)print(adata)AnnData object with n_obs × n_vars = 3 × 2 obs: 'condition' layers: None (.X)Access the count matrix with .X.
print(adata.X)[[100 250] [120 300] [ 90 280]]Access observation metadata with .obs.
print(adata.obs) conditionSample1 controlSample2 treatedSample3 treatedAn observation filter selects the corresponding matrix rows and observation metadata. The explicit colon retains every variable.
treated = adata[adata.obs["condition"] == "treated", :]print(treated)print(treated.obs_names.tolist())print(treated.X)View of AnnData object with n_obs × n_vars = 2 × 2 obs: 'condition' layers: None (.X)['Sample2', 'Sample3'][[120 300] [ 90 280]]The subset preserves the correspondence between these rows and their sample
labels. It cannot detect an incorrect label assigned when the object was
created. Use .copy() when the selected data must become an independent
AnnData object rather than a view.
Practice before an interview
Section titled “Practice before an interview”Answer these questions before opening the explanation. State which objects exist and which references point to them; a predicted output alone does not explain the behavior.
| Question | What to explain |
|---|---|
Two RunLog instances exist. What happens when one event list changes? |
Contrast an instance list with the list on SharedRunLog. |
Two Sample records have identical fields. Can both enter a set? |
Distinguish equality from hashability. |
A subclass inherits ReadBatch.from_tsv. Which class does the factory return? |
Explain the role of cls and the initializer contract. |
| Two nodes contain the same integer. Does visiting both establish a cycle? | Decide whether the visited set should store values or identities. |
A caller passes one notes list to two SampleNotes instances. Does the factory copy it? |
Explain when the default factory runs. |
Read the explanations and run the checks
Each RunLog initializer creates a list, so changing one list leaves the other
unchanged. SharedRunLog instead finds one list on the class until an instance
shadows that attribute.
Default Sample records compare by their fields, but they are mutable and
unhashable. Equality alone does not permit insertion into a set.
The class method receives the subclass as cls. Because the subclass below
inherits the same initializer, the factory returns a valid subclass instance.
Two equal node values do not establish a cycle. A cycle requires traversal to reach a previously visited node object. A supplied notes list remains shared because the default factory runs only when the argument is omitted.
class SequencingBatch(ReadBatch): """Retain the ReadBatch initializer and inherit its alternate factory."""
exercise_log_one = RunLog()exercise_log_two = RunLog()exercise_log_one.events.append("count")assert exercise_log_two.events == []assert SharedRunLog().events is SharedRunLog().events
exercise_sample = Sample("S8", "control", 10)assert exercise_sample == Sample("S8", "control", 10)assert Sample.__hash__ is None
exercise_batch = SequencingBatch.from_tsv("S7\t14")assert type(exercise_batch) is SequencingBatchassert exercise_batch.read_count == 14
exercise_head = Node(5, Node(5))assert not has_cycle(exercise_head)exercise_head.next.next = exercise_headassert has_cycle(exercise_head)
exercise_notes: list[str] = []exercise_one = SampleNotes("S8", exercise_notes)exercise_two = SampleNotes("S9", exercise_notes)assert exercise_one.notes is exercise_two.notesprint("Factory result:", type(exercise_batch).__name__)print("All five exercise checks passed.")Factory result: SequencingBatchAll five exercise checks passed.Quick reference
Section titled “Quick reference”| Concept | Syntax | Use case |
|---|---|---|
| Class | class Gene: |
Bundle data and behavior |
| Initializer | def __init__(self, ...): |
Initialize an already created instance |
| Method | def is_expressed(self): |
Define behavior on the instance |
__str__ |
def __str__(self): |
Human-readable string for print() |
__repr__ |
def __repr__(self): |
Developer string for debugging |
| Inheritance | class DifferentialGene(Gene): |
Extend a class with new features |
super() |
super().__init__(...) |
Continue lookup through the method resolution order |
| Property | @property and @name.setter |
Control attribute access and validate assignments |
| Class method | @classmethod with cls |
Construct through the receiving class |
| Static method | @staticmethod |
Group a related operation that needs no object state |
| Dataclass | @dataclass |
Generate field-based initialization and equality |
| Independent default | field(default_factory=list) |
Create a list when the argument is omitted |
| Initial validation | __post_init__ |
Check fields after generated initialization |
| Value key | @dataclass(frozen=True) |
Support stable keys when fields are immutable and hashable |
| Identity node | @dataclass(eq=False) |
Retain object identity semantics when inherited from object |
| Collection protocol | __len__ and __iter__ |
Support size queries and iteration |
The tree and linked-list interview lessons use classes to represent nodes. Those examples show how object references define the structure an algorithm traverses.
Further reading
Section titled “Further reading”The Python 3.13 class tutorial explains instance attributes, class attributes, method binding, and inheritance. Use its class-variable discussion to review the shared-list mistake.
The dataclass reference defines generated equality, hash rules, default factories, and post-initialization hooks. Check those rules before using a dataclass as a dictionary key.
The copy reference distinguishes assignment, shallow copies, and deep copies. It also explains why some objects cannot or should not be copied recursively.
The data model reference defines identity, equality, hashing, and special methods. Its container methods explain how a custom class participates in ordinary Python operations.
The built-in function reference
documents property, classmethod, staticmethod, and super.
The Self annotation
describes the return type of factories that preserve the receiving class.
The AnnData tutorial explains the matrix, obs, and var components used in the AnnData example. See Getting started with anndata.