Companions and Class State
Lesson 35 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin companion objects hold class-associated state, while ordinary declared properties belong to instances. Python class-body assignments define class attributes visible through instance lookup. An instance assignment can shadow a class attribute without changing it for other instances. Mutating a shared class-level list differs from assigning an instance attribute: mutation changes the one list.
Kotlin
class Shelf { companion object { var category = "books" } }
fun main() {
println(Shelf.category)
Shelf.category = "tools"
println(Shelf.category)
}Python
class Shelf:
category = "books"
a = Shelf()
b = Shelf()
a.category = "tools"
print(a.category, b.category, Shelf.category)Porting trap
Python class attributes are not Kotlin companion objects with a separate declared object. Put per-instance mutable values inside __init__ and use class access deliberately for shared state.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking7Instances and Shared State
Classes and Attribute AccessConstructors and Fresh StateReceivers and Bound MethodsCompanions and Class StateProperty Accessors and TextRecap: Model a Bank Account2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler