Menu
CoddyTech

Initialize Instance State

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

Initialize attributes on each new instance.

C# reference excerpt

Executable statements use C# top-level program style; type-only examples are declarations. System names assume the usual using System directive.

var board = new Board("home");
Console.WriteLine(board.Points);
class Board {
    public int Points;
    public Board(string name, int points = 0) { Points = points; }
}

Python

class Board:
    def __init__(self, name, points=0):
        self.name = name
        self.points = points

board = Board("home")
print(board.points)

What changes

Calling a class creates an instance and invokes initialization. __init__ initializes an already allocated instance; __new__ handles creation and is outside this course. self names the instance receiving attributes, unlike C# implicit this. Store per-object data through self. Python __init__ must return None, so do not return the object from it.

Transfer mistake

Assigning points = points inside __init__ only rebinds a local parameter. self.points = points creates the instance attribute. No constructor overload selection is implied by multiple same-named definitions.

Your task

Implement Scoreboard(name, points=0) with independent name and points attributes. The driver reads a name, initial integer score, and integer bonus; scores may be negative. It constructs that board and a guest board with the default score, changes only the first, and prints both name:points lines.

challenge icon

Challenge

Beginner

Implement Scoreboard(name, points=0) with independent name and points attributes. The driver reads a name, initial integer score, and integer bonus; scores may be negative. It constructs that board and a guest board with the default score, changes only the first, and prints both name:points lines.

Editable implementation files: scoreboard.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation 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 C# Developers

Practice on your own: Online Python compiler