Construction and State
Lesson 33 of 48 in Coddy's Python for JavaScript Developers course.
Initialize every instance with the state its methods will need. A constructor call can accept arguments so callers do not have to remember several separate attribute assignments. This gives objects a useful starting state before they are returned to the caller.
JavaScript
class Label {
constructor(text = "untitled") { this.text = text; }
}
const a = new Label("draft");
const b = new Label();
console.log(a.text, b.text);Python
class Label:
def __init__(self, text="untitled"):
self.text = text
a = Label("draft")
b = Label()
print(a.text, b.text)What changes
Both programs print draft untitled. Python invokes __init__ to initialize an instance after it has been created; this method is not the allocation mechanism. Its first parameter receives that instance. By convention we name it self. A caller supplies the text argument but does not pass self explicitly. Writing self.text = text stores the parameter as an instance attribute. A plain local assignment would disappear when initialization finishes. Do not return a replacement object from __init__; normally it ends without a return statement.
Common mistake
Default arguments follow the function rules you already learned. A mutable list used as a default is shared across calls. Prefer None and create a new list during initialization. If callers supply a list and you promise independent storage, copy that list too; a safe default alone does not prevent aliasing.
Your task
Build scoreboards whose supplied scores and default scores remain independent. Use initialization to establish attributes before the driver updates them.
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 JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking7Objects and Classes
Objects and InstancesConstruction and StateMethods and selfClass and Instance AttributesProperties and Object TextRecap: Model a Bank Account2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler