Menu
CoddyTech

Class and Instance Attributes

Lesson 35 of 48 in Coddy's Python for C# Developers course.

Separate shared class defaults from per-instance mutable state.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

class Playlist {
    public static string Category = "music";
    public System.Collections.Generic.List<string> Tracks = new System.Collections.Generic.List<string>();
}

Python

class Playlist:
    category = "music"
    def __init__(self):
        self.tracks = []

a = Playlist()
a.category = "talk"
print(Playlist.category, a.category)

What changes

A Python class attribute supplies a fallback through instance lookup. Assigning a.category creates an instance attribute that shadows the class value; it does not update Playlist.category. This differs from C# static members, which are accessed through the type. A mutable list in the Python class body would be shared by instances that use it. Create each tracks list in __init__.

Transfer mistake

Calling self.tracks.append does not create an instance list if lookup found a class list. Mutation changes the shared object. Use self.tracks = [] during initialization.

Your task

Implement Playlist with class attribute category = "music", an independent tracks list for every instance, and add(track) to append a string. The driver reads two track-token lines, possibly empty, and a category label. It fills two playlists and assigns the new category only to the first instance. It prints category:comma-joined-tracks for both, followed by Playlist.category. Track tokens contain neither spaces nor commas.

challenge icon

Challenge

Beginner

Implement Playlist with class attribute category = "music", an independent tracks list for every instance, and add(track) to append a string. The driver reads two track-token lines, possibly empty, and a category label. It fills two playlists and assigns the new category only to the first instance. It prints category:comma-joined-tracks for both, followed by Playlist.category. Track tokens contain neither spaces nor commas.

Editable implementation files: playlist.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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 C# Developers

Practice on your own: Online Python compiler