Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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)
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