Menu
CoddyTech

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 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 Dart Developers

Practice on your own: Online Python compiler