Menu
CoddyTech

Initializing Instance State

Lesson 33 of 48 in Coddy's Python for Java Developers course.

Initialize the current object in __init__. Java constructors use the class name and implicit this; Python uses the conventional explicit parameter self and writes instance attributes as self.name. Calling Score(5) supplies 5 after Python binds the new instance as self. __init__ initializes an existing instance; allocation is handled separately, normally by __new__. It must return None rather than the instance. Defaults can replace simple Java constructor overloads, but retain Python's definition-time evaluation rule.

Java excerpt: class member declarations

// Class member
static class Score {
    int points;
    Score(int points) { this.points = points; }
}

Python

class Score:
    def __init__(self, points=0):
        self.points = points
a = Score(5)
b = Score()
print(a.points, b.points)

Watch the difference

Writing points = points only rebinds a local parameter. Use self.points to persist state. Put mutable per-instance collections in __init__, creating a fresh list for each instance rather than sharing a default.

Practice

Apply this comparison in the task below. Editable files: scoreboard.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

Implement Scoreboard(name, points=0) in scoreboard.py with independent name and points attributes. The driver reads a name, initial integer score, and integer bonus; creates that board and a default guest board; adds the bonus only to the first; and prints both name:points lines. Negative scores and bonuses are valid. A Python default replaces a Java no-score constructor overload.

Editable files: scoreboard.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

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

Practice on your own: Online Python compiler