Class Lookup and Shared Lists
Lesson 35 of 48 in Coddy's Python for R Developers course.
Python instance attribute lookup can fall back to attributes on its class. A list allocated in the class body is one shared object, not a separate field allocation for every instance. Assignment on one instance usually shadows the class attribute, while mutation through the inherited reference affects the shared object. R list-based constructors often allocate independent values; R environments make shared mutation explicit. Neither comparison should obscure Python's lookup rule. Put a fresh mutable container inside __init__ when state belongs to each instance. Use class attributes for genuinely shared configuration, with care around mutation.
R
make_bag <- function() list(items=character(0))
a <- make_bag()
b <- make_bag()
a$items <- c(a$items, "x")
cat(length(b$items), "\n", sep="")Python
class Bag:
items = []
a = Bag()
b = Bag()
a.items.append('x')
print(b.items)
a.items = ['y']
print(b.items)Porting trap
A Python class-body list is executable allocation at class definition time. It is not a typed field declaration that will allocate later per instance.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking7Objects and Shared State
R Objects and Python ClassesInitializing Instance StateReceiver Methods and GenericsClass Lookup and Shared ListsValidated Attribute AccessRecap: Model a Bank Account2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler