Shared and Instance State
Lesson 35 of 48 in Coddy's Python for C++ Developers course.
A Python class body can define shared attributes. Instance lookup can fall back to that class attribute; assigning a.category ordinarily creates an instance attribute that shadows it. C++ static members stay static even when accessed through an object, so a.category assignment there would change the shared member instead. A Python list stored in the class body is shared until shadowed, while self.items = [] in __init__ creates a list per instance.
C++17: declarations and main
Standard-library headers are supplied in the runnable companion program.
struct Bag {
inline static std::string category = "tools";
std::vector<int> items;
};
int main() {
Bag a, b;
a.items.push_back(1);
std::cout << a.items.size() << ' ' << b.items.size() << ' ' << Bag::category << '\n';
}Python
class Bag:
category = "tools"
def __init__(self):
self.items = []
a, b = Bag(), Bag()
a.category = "books"
print(a.category, b.category, Bag.category)Porting trap
Appending through a shared class list does not create a new instance list. Mutation and attribute assignment are different operations.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
Challenge
BeginnerImplement Playlist with class attribute category = "music", a fresh instance list tracks, and method add(track) that appends one string. Input has two space-separated track lines, either possibly empty, followed by a category label. The driver builds two playlists, fills them independently, and assigns the new category only to the first instance. Print each instance's category and comma-joined tracks as category:tracks, then Playlist.category. Track names have no commas or spaces.
The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.
Your code goes in the editable files playlist.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable modules.
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++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Instances Without newInitialization and Ownershipthis and Bound MethodsShared and Instance StateProperties and Object TextRecap: Model a Bank Account2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler