Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for PHP Developers

Practice on your own: Online Python compiler