Value Models and Identity
Lesson 41 of 48 in Coddy's Python for GDScript Developers course.
Two separate GDScript RefCounted objects are distinct even when their fields match; an explicit method can compare the fields. Python ordinary classes also need a custom value comparison when identity is not the intended equality. A dataclass can generate initialization, representation and field-based equality. Python is remains an identity check. Custom __eq__ returns NotImplemented for unsupported types.
GDScript
extends SceneTree
class Point extends RefCounted:
var x
var y
func _init(px, py):
x = px
y = py
func same_value(other):
return x == other.x and y == other.y
func _init():
var a = Point.new(1, 2)
var b = Point.new(1, 2)
print(a.same_value(b))
print(a == b)
quit()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
A mutable dataclass is normally unhashable. Generated equality does not make mutable objects safe set members, nor does it provide Godot Resource serialization.
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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules5Functions and Closures
Func, Def, and Returned ValuesKeyword Calls and DefaultsCallv and Python UnpackingCaptured Values and CallablesRecap: Refactor a Pricing Tool8Composition and Dispatch
RefCounted CollaboratorsExtends and Method LookupBehavior Without Scene TypesValue Models and IdentityRecap: Notification Channels3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler