Initializing Object State
Lesson 33 of 48 in Coddy's Python for C Developers course.
C often initializes a struct with an initializer or a factory function returning a struct value. Python __init__ initializes an already created instance, receiving it as self. Assign each piece of per-instance state through self so two objects remain independent. Defaults can reduce repeated factory variants, but __init__ must return None rather than the initialized object. Calling Score twice creates two separate instances here; assigning b = a would instead share one.
C: complete example.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
struct Score { int points; };
struct Score make_score(int points) { struct Score s = {points}; return s; }
int main(void) {
struct Score a = make_score(4); struct Score b = make_score(0);
a.points += 3;
printf("%d %d\n", a.points, b.points);
return 0;
}Python: complete example.py
class Score:
def __init__(self, points=0):
self.points = points
a = Score(4)
b = Score()
a.points += 3
print(a.points, b.points)Watch the difference
If a class needs a fresh list for each instance, create it inside __init__. A mutable class attribute would be shared, and a mutable default parameter can also be reused across calls.
Your code goes in scoreboard.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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.
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.
Create per-instance state during initialization rather than accidentally sharing a class-level object.
Your code goes in scoreboard.py. The locked driver.py is the entry file, supplies execution and checks, and cannot be edited.
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 Programs to Python
Run Python Without mainPrinting Without Format CodesNames Versus Typed StorageDivision and Integer LimitsSuites Instead of BracesRecap: A Python Receipt4Iteration and Transformations
Iteration Without PointersIndexes Without Pointer MathSentinels and Loop ControlComprehensions and SortingRecap: Stable Ranking7Structs to Python Objects
Allocation and Object LifetimeInitializing Object StateBound Methods Versus CallbacksShared State and ShadowingProperties and Validated StateRecap: Account State2Values and Truth Tests
Absence Is Not a Null PointerContent Versus Object IdentityTruth Tests and OperandsConditional Value SelectionRecap: Missing or Eligible3Containers and Aliasing
Lists Versus C ArraysTuples and Struct ValuesMappings and Lookup LoopsPointers, Copies, and AliasesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputError Codes Versus ExceptionsImports Are Not IncludesAnnotations Versus C TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler