Shared State and Shadowing
Lesson 35 of 48 in Coddy's Python for C Developers course.
C can put shared data in a file-scope object and individual values in each struct, but it has no built-in instance-to-class attribute lookup. Python first finds an ordinary instance attribute such as score; absent a category instance attribute, lookup reaches the class attribute. Assigning a.category here creates an instance attribute that shadows the class value. It leaves b and Player.category unchanged. Mutating a list found on the class would instead change the one shared list.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
static int category = 7;
struct Player { int score; };
int main(void) {
struct Player a = {0}; struct Player b = {0};
a.score = 4;
printf("%d %d %d\n", category, a.score, b.score);
return 0;
}Python: complete example.py
class Player:
category = "game"
def __init__(self):
self.score = 0
a = Player()
b = Player()
a.category = "custom"
print(a.category, b.category, Player.category)Watch the difference
A C static storage-duration variable and a Python class attribute are not equivalent access mechanisms. Avoid placing mutable per-object state at class scope. Use __init__ for the tracks list in the task.
Your code goes in playlist.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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.
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.
A Python instance can shadow an ordinary class attribute; C structs do not have this fallback lookup mechanism.
Your code goes in playlist.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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 C Developers
1From C Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking7Structs to Python Objects
Allocation and Object LifetimeInitializing Object StateBound Methods Versus CallbacksShared State and ShadowingProperties and Validated StateRecap: Account State2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler