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
BeginnerImplement 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}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking7Instance and Class State
Instances Without newInitializing Instance StateBound Methods and selfClass State Is Not a FieldProperties and Access ControlRecap: Account State2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler