Constructors and Fresh Lists
Lesson 33 of 48 in Coddy's Python for PHP Developers course.
PHP initializes objects with __construct; Python initializes a new instance with __init__. Python explicitly names the instance parameter, conventionally self. Put per-instance mutable state inside initialization so each object receives its own list. Unlike PHP's declared instance-property defaults, a list assigned directly in a Python class body is shared through the class until shadowed. Python __init__ initializes an already created instance and must not return a replacement object.
PHP 8.3
<?php
class Bag {
public $items = [];
}
$a = new Bag(); $b = new Bag();
$a->items[] = 'pen';
echo count($a->items), ' ', count($b->items), "\n";Python
class Bag:
def __init__(self):
self.items = []
a = Bag()
b = Bag()
a.items.append("pen")
print(len(a.items), len(b.items))Porting trap
A default parameter list is also shared, so def __init__(self, items=[]) has the same default-state trap as other functions. Use None and construct a list inside when callers omit it.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking7Instances and Shared State
Instances Without newConstructors and Fresh ListsThis and Bound MethodsStatic and Instance AttributesProperties and Object TextRecap: Model a Bank Account2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler