Class and Instance Attributes
Lesson 35 of 48 in Coddy's Python for JavaScript Developers course.
Separate shared class defaults from mutable state that belongs to one instance. This distinction matters whenever several objects live together: an accidental shared list can make unrelated objects appear to change each other.
JavaScript
class Group {
static category = "team";
constructor() { this.members = []; }
}
const a = new Group(), b = new Group();
a.members.push("Kai");
console.log(a.members.length, b.members.length);
console.log(Group.category);Python
class Group:
category = "team"
def __init__(self):
self.members = []
a, b = Group(), Group()
a.members.append("Kai")
print(len(a.members), len(b.members))
print(Group.category)What changes
Both programs print 1 0 and then team. The shared label sits on the class, while initialization creates an independent members list. Python can also find this ordinary class attribute through an instance, such as a.category. A JavaScript static field is accessed on the class; it is not an instance field. In Python, assigning a.category = "solo" creates an instance attribute that shadows the class default. Changing Group.category later affects lookup on instances that have not shadowed it.
Common mistake
Putting members = [] directly in the Python class body creates one list. Appending through either instance mutates that shared list. This differs from assigning a new instance attribute: mutation changes the object found by lookup, while assignment can establish a separate attribute. Create per-instance lists inside __init__.
Your task
Give each playlist its own tracks while retaining a shared category default. The driver checks both isolated mutations and instance-level shadowing.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking7Objects and Classes
Objects and InstancesConstruction and StateMethods and selfClass and Instance AttributesProperties and Object TextRecap: Model a Bank Account2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler