Menu
CoddyTech

Structs and Data Classes

Lesson 41 of 48 in Coddy's Python for Go Developers course.

Go structs with comparable fields support field-wise ==; a struct containing a slice is not comparable. A plain Python class instead starts with identity-based equality. dataclass generates initialization, representation, and field equality for common data holders, but does not enforce annotation types. By default it is mutable. The task practices manual __eq__ so you can see the protocol rather than relying on generated behavior.

Go

Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.

type Point struct { X, Y int }
// Inside main:
a := Point{X: 2, Y: 3}
b := a
fmt.Println(a == b)
b.Y++
fmt.Println(a == b)

Python

from dataclasses import dataclass
@dataclass
class Point:
    x: int
    y: int
a = Point(2, 3)
b = Point(2, 3)
print(a == b)
print(a is b)
b.y += 1
print(a == b)

Porting trap

Return NotImplemented for unsupported comparison operand types, letting Python try the other operand or fallback. Do not raise NotImplementedError or return its name as text. Defining value equality also affects hashing; do not assume a mutable value object can be a dict key.

challenge icon

Challenge

Beginner

Implement mutable Coordinate(x,y) with __eq__: compare x and y when other is a Coordinate (check with isinstance), otherwise return NotImplemented. The driver creates two coordinates from two integer-pair lines, prints equality and identity, increments the second y, prints equality again, then equality with None. Finally it checks directly that a.__eq__(None) is NotImplemented and prints True. Go comparable structs supply field equality; this Python task deliberately implements the __eq__ protocol manually.

Editable files: coordinate.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Go Developers

Practice on your own: Online Python compiler