Initialization and Ownership
Lesson 33 of 48 in Coddy's Python for Rust Developers course.
Python usually initializes attributes in __init__(self, ...), which runs after the instance is created. It must return None, not the instance. Rust often uses an associated new function returning Self; that name has no special language privilege. Constructing two Python instances calls initialization twice, so attributes assigned there can be independent. When storing a passed mutable object, Python retains its reference rather than transferring ownership. Copy deliberately when independent state is required.
Rust excerpt inside main
struct Score { points: i32 }
impl Score { fn new(points: i32) -> Self { Self { points } } }
let a = Score::new(5);
let b = Score::new(0);
println!("{} {}", a.points, b.points);Python
class Score:
def __init__(self, points=0):
self.points = points
a = Score(5)
b = Score()
print(a.points, b.points)Porting trap
Creating self.items = [] per initialization gives independent lists. Moving the list to the class body would share one mutable default among instances unless shadowed.
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 Scoreboard(name, points=0) with instance attributes name and points. Input is a name, an integer initial score, and an integer bonus on separate lines. The driver constructs one named board with that score and another named guest using the default, adds the bonus to the first, and prints name:points for each. Scores and bonuses may be negative. Initialization must store the supplied values independently.
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 scoreboard.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 scoreboard import Scoreboard
board = Scoreboard(input(), int(input()))
guest = Scoreboard("guest")
board.points += int(input())
print(f"{board.name}:{board.points}")
print(f"{guest.name}:{guest.points}")
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