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
BeginnerIn 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking7Structs to Python Classes
From Structs to InstancesInitialization and Fresh StateReceivers and Bound MethodsClass State and ShadowingProperties and Display HooksRecap: Account State2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler