Initialization and Ownership
Lesson 33 of 48 in Coddy's Python for C++ Developers course.
Python __init__ initializes an already created instance; it must return None. C++ constructor initializer lists initialize members before the constructor body; Python attributes are assigned by ordinary statements such as self.points = points. Put a fresh list in __init__ for independent per-instance state. C++ ownership may be embedded by value or expressed through smart pointers; Python references do not encode unique ownership or a move operation.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
struct Score {
int points;
explicit Score(int initial = 0) : points(initial) {}
};
Score a(5), b;
std::cout << a.points << ' ' << b.points << '\n';Python
class Score:
def __init__(self, points=0):
self.points = points
a = Score(5)
b = Score()
print(a.points, b.points)Porting trap
__init__ is not a destructor pair. Resource cleanup belongs in a context manager when it must happen at a known point; deleting a name only removes that binding.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and API names.
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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Instances Without newInitialization and Ownershipthis and Bound MethodsShared and Instance StateProperties and Object TextRecap: Model a Bank Account2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler