Class Fields and Lookup
Lesson 35 of 48 in Coddy's Python for Dart Developers course.
Dart fields declared without static belong to instances and receive their initialization per instance. Python assignments in a class body create class attributes, which instances can find through fallback lookup. A mutable class-body list is therefore shared. Assigning an attribute on one Python instance usually shadows the class value; mutating the inherited list changes the shared object. Dart static fields are accessed through the class rather than via ordinary instance fallback in the same way. To reproduce a Dart per-instance collection field, create self.tracks inside Python __init__. Keep shared configuration distinct from mutable instance state.
Dart
class Bag {
final items = <String>[];
}
void main() {
final a = Bag();
final b = Bag();
a.items.add('x');
print(b.items);
}Python
class Bag:
items = []
a = Bag()
b = Bag()
a.items.append('x')
print(b.items)
a.items = ['y']
print(b.items)Porting trap
The visually similar class-body list declarations have different allocation semantics. Move mutable Python instance state into __init__.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking7Objects and Shared State
Declared Fields and AttributesConstructors and __init__this and Bound MethodsClass Fields and LookupGetters, Setters, and __str__Recap: Model a Bank Account2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler