Class State and Shadowing
Lesson 35 of 48 in Coddy's Python for Go Developers course.
Go struct fields belong to each struct value; package variables can hold shared state. Python class attributes live on the class and can be found through instances that have not shadowed them. Assigning a.category creates an instance attribute here, leaving the class and other instances unchanged. That is different from updating a package variable and different from Go struct field initialization.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Playlist struct { Category string }
// Inside main:
a := Playlist{Category: "music"}
b := Playlist{Category: "music"}
a.Category = "talk"
fmt.Println(a.Category, b.Category)Python
class Playlist:
category = "music"
a = Playlist()
b = Playlist()
a.category = "talk"
print(a.category, b.category, Playlist.category)Porting trap
A mutable class attribute is shared until explicitly shadowed. Calling self.tracks.append on a class-level tracks list mutates the shared list; it does not create per-instance state.
Challenge
BeginnerImplement Playlist with class attribute category = "music", a new tracks list per instance, and add(track) appending a string. The driver reads two possibly empty space-separated track lists and a category, fills two playlists, and reassigns category on the first instance only. It prints each category:comma-joined-tracks, then Playlist.category. Track names contain no commas or spaces. Go has struct fields and package state; Python instance assignment here shadows the class attribute without replacing it.
Editable files: playlist.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 playlist import Playlist
a, b = Playlist(), Playlist()
for track in input().split():
a.add(track)
for track in input().split():
b.add(track)
a.category = input()
print(f"{a.category}:{','.join(a.tracks)}")
print(f"{b.category}:{','.join(b.tracks)}")
print(Playlist.category)
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