init to __init__
Lesson 33 of 48 in Coddy's Python for Swift Developers course.
Swift initializers establish instance state. Python __init__ initializes an instance that has already been created and must return None. Assigning self.points sets per-instance state. Calling the class twice runs initialization twice, so distinct objects can have different values. Mutable per-instance lists should be created inside the initializer. If a supplied list is stored directly, its reference remains shared with the caller rather than receiving Swift Array value semantics.
Swift example
final class Score {
var points: Int
init(points: Int = 0) { self.points = points }
}
let a = Score(points: 5)
let b = Score()
print(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
Python default argument objects are shared across calls, so avoid using a mutable default list as instance state.
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 Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs and Dynamic Attributesinit to __init__self and Method ReferencesType Properties and ShadowingComputed Properties and TextRecap: Model a Bank Account2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler