Class and Instance State
Lesson 35 of 48 in Coddy's Python for Rust Developers course.
Python class-body attributes are found through the class when an instance lacks its own attribute. Assigning a.category normally creates an instance attribute that shadows the class attribute; other instances still see the class value. Rust associated constants belong to the type and cannot be shadowed by inventing a field on one value. Keep per-instance mutable lists inside __init__; a list created in the Python class body is shared by attribute lookup.
Rust excerpt inside main
struct Bag { items: Vec<i32> }
impl Bag { const CATEGORY: &'static str = "tools"; }
let mut a = Bag { items: Vec::new() };
let b = Bag { items: Vec::new() };
a.items.push(1);
println!("{} {} {}", a.items.len(), b.items.len(), 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
Mutating a shared class list and assigning a new instance list are different operations. The former affects all aliases; the latter changes only that instance's lookup.
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
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs to InstancesInitialization and Ownershipself and Bound MethodsClass and Instance StateProperties and DisplayRecap: Model a Bank Account2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler