Constructors and Fresh State
Lesson 33 of 48 in Coddy's Python for Lua Developers course.
A Lua constructor is commonly a regular function returning a new table. Python class calls create instances and then invoke __init__ to initialize them. The initializer should return None, not the instance. Assign per-instance mutable collections inside __init__ so each construction gets a fresh object. Storing a supplied list shares it unless copied, just as storing a Lua table reference shares that table. Defaults and class attributes must be chosen with that aliasing in mind.
Lua example
local function score(points)
return {points = points or 0}
end
local a, b = score(5), 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
Do not translate a Lua constructor's return self into a Python __init__ return. Python already created the object before initialization.
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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking7Classes Beyond Metatables
Tables to Class InstancesConstructors and Fresh StateColon Calls to Bound MethodsLookup and Shared DefaultsProperties and tostringRecap: Model a Bank Account2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler