Menu
CoddyTech

From Structs to Instances

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

Go struct values have declared fields and assignment copies the struct value, though any pointer-like fields may still share data. Ordinary Python class instances can receive attributes through assignment. Calling Parcel() creates a new instance; assigning that instance to another name shares it. To create independent Python objects, call the class again. A plain class does not supply automatic field declarations or a Go-style struct literal constructor.

Go

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

type Parcel struct { Label string; Weight int }
// Inside main:
a := Parcel{Label: "red", Weight: 2}
b := a
b.Weight = 7
fmt.Println(a.Weight, b.Weight)

Python

class Parcel:
    pass
a = Parcel()
a.label = "red"
a.weight = 2
b = a
b.weight = 7
print(a.weight, b.weight)
print(a is b)

Porting trap

Do not expect b = a to copy an instance the way Go struct assignment copies a value. Python has no general new keyword; the class call is the construction syntax.

challenge icon

Challenge

Beginner

In parcel.py define an empty Parcel class with pass. In functions.py implement make_parcel(label, weight), creating a fresh Parcel, setting label and weight, and returning it. The driver reads two label/weight pairs and an increase (all weights and increases nonnegative; labels may be empty), increases only the first parcel, prints both label:weight lines, then prints their identity comparison. Go struct fields are declared; ordinary Python instances here receive attributes through assignment.

Editable files: parcel.py, functions.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 parcel import Parcel
from functions import make_parcel

a = make_parcel(input(), int(input()))
b = make_parcel(input(), int(input()))
assert isinstance(a, Parcel) and isinstance(b, Parcel)
a.weight += int(input())
print(f"{a.label}:{a.weight}")
print(f"{b.label}:{b.weight}")
print(a is b)
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