Menu
CoddyTech

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 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.

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}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for C Developers

Practice on your own: Online Python compiler