Shared Class State
Lesson 35 of 48 in Coddy's Python for Ruby Developers course.
Ruby distinguishes instance variables, class instance variables, and class variables written with two at-signs. Do not collapse these into one Python rule. Python class attributes are found through instance lookup when no instance attribute shadows them. A mutable object stored in the class body is consequently shared through that lookup. Assigning an attribute on one instance usually creates a shadowing instance attribute; it does not replace the class attribute. Ruby class variables have inheritance-wide sharing behavior that is not identical to Python lookup. For per-instance collections, allocate in __init__, as you would allocate an instance array in Ruby initialize.
Ruby
class Bag
def initialize
@items = []
end
attr_reader :items
end
a = Bag.new
b = Bag.new
a.items << 'x'
p b.itemsPython
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 not shorthand for an instance field declaration. All instances can mutate the same list until you deliberately create separate lists.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking7Objects and Shared State
Objects and Public Attributesinitialize and __init__Explicit self ParametersShared Class StateReaders, Writers, and strRecap: Model a Bank Account2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler