Data Classes and Equality
Lesson 41 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin data classes generate value equality from primary-constructor properties. Python dataclasses generate comparable behavior from declared fields, while ordinary Python classes default to identity equality unless customized. Equal field values do not make two instances identical. Python custom __eq__ should return NotImplemented for unsupported types so the comparison protocol can continue. Mutable dataclasses are normally unhashable.
Kotlin
data class Point(val x: Int, val y: Int)
fun main() {
val a = Point(1, 2); val b = Point(1, 2)
println(a == b)
println(a === b)
}Python
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
a = Point(1, 2)
b = Point(1, 2)
print(a == b)
print(a is b)Porting trap
Do not infer a deep copy from either data-class construction or a shallow copy operation. Nested mutable state can remain shared even when outer instances compare equal.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
Challenge
BeginnerImplement Coordinate(x, y) with value equality: __eq__(other) compares both stored integer coordinates when other is a Coordinate; otherwise return NotImplemented. Input has two lines, each containing two integers. The driver creates two independent coordinates, prints their equality and identity, increments the second coordinate's y, prints equality again, and finally compares the first coordinate with None. Use isinstance(other, Coordinate) before accessing the other coordinates. Return booleans from the supported comparison, not strings.
The locked driver handles input and output. Submit only the required class and function definitions with the exact API names. Do not read input or print from your classes.
The driver also calls a.__eq__(None) directly and prints whether the result is NotImplemented; the final line must be True.
Your code goes in the editable files coordinate.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.
Try it yourself
from coordinate import Coordinate
x, y = [int(v) for v in input().split()]
a = Coordinate(x, y)
x, y = [int(v) for v in input().split()]
b = Coordinate(x, y)
print(a == b)
print(a is b)
b.y += 1
print(a == b)
print(a == None)
print(a.__eq__(None) is NotImplemented)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ListsDefaults and Named CallsVararg and Keyword PackingClosures and Lambda ResultsRecap: Refactor a Pricing Tool8Composition and Dispatch
Injected CollaboratorsOpen Classes and superInterfaces and BehaviorData Classes and EqualityRecap: Notification Channels3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler