Menu
CoddyTech

Lookup and Shared Defaults

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

Lua __index can fall back from an object table to a prototype table. Python normal instance lookup similarly finds a class attribute when no instance attribute shadows it, though Python uses its own descriptor and class lookup protocol. Assigning a.category creates an instance value while b continues to use the class value. A mutable list stored on the class is shared until instances shadow it. Initialize mutable per-instance state in __init__.

Lua example

local Bag = {category = "tools"}
local a = setmetatable({}, {__index = Bag})
local b = setmetatable({}, {__index = Bag})
a.category = "books"
print(a.category .. " " .. b.category .. " " .. Bag.category)

Python

class Bag:
    category = "tools"
    def __init__(self):
        self.items = []
a, b = Bag(), Bag()
a.category = "books"
print(a.category, b.category, Bag.category)

Porting trap

Appending to a class-provided list mutates the shared object; assigning a new list to an instance changes that instance's lookup instead.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

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 Lua Developers

Practice on your own: Online Python compiler