Constructors and __init__
Lesson 33 of 48 in Coddy's Python for Dart Developers course.
Dart generative constructors initialize declared fields and can use initializing formals. Python construction typically calls __init__ with the new instance as self. Assign attributes explicitly on self; assigning only a local name does not store instance state. Python __init__ must return None, not the instance. Dart named constructors and factory constructors do not translate into multiple Python __init__ definitions; use a classmethod or a separate factory function when alternative construction is needed. Allocate mutable per-instance containers during initialization, not in a class-body declaration or reused default argument.
Dart
class Counter {
int value;
Counter([this.value = 0]);
}
void main() {
final a = Counter(5);
final b = Counter();
print('${a.value} ${b.value}');
}Python
class Counter:
def __init__(self, value=0):
self.value = value
a = Counter(5)
b = Counter()
print(a.value, b.value)Porting trap
Python does not overload __init__ by signature. A later definition with the same name replaces the earlier one.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking7Objects and Shared State
Declared Fields and AttributesConstructors and __init__this and Bound MethodsClass Fields and LookupGetters, Setters, and __str__Recap: Model a Bank Account2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler