Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Dart Developers

Practice on your own: Online Python compiler