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
BeginnerImplement 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking7Objects and Properties
Instances Across ModulesInitialize Instance StateBound Methods and selfClass and Instance AttributesProperties and Access RulesRecap: Independent Accounts2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler