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
BeginnerImplement 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}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for C# Developers
1C# Foundations in Python
Run the Python WorkspaceOutput, Strings, and CommentsTyped Locals to Python NamesDivision and RemaindersIndentation Instead of BracesRecap: Port a Receipt4Loops and Transformations
From foreach to forIndexes and Dictionary ItemsSentinels and Loop ControlFrom LINQ to ComprehensionsRecap: Stable Ranking7Objects and Properties
Instances Across ModulesInitialize Instance StateBound Methods and selfClass and Instance AttributesProperties and Access RulesRecap: Independent Accounts2None and Decisions
Nullable Values and NoneEquality, Identity, and TypesTruth Tests and FallbacksBranch PriorityRecap: Eligibility Rules3Collections and References
From List<T> to listTuples and UnpackingDictionary Keys and ValuesSets, Aliases, and CopiesRecap: Stock Lookup6Reliable Python Programs
Input and Exact OutputExceptions and ValidationImports and the Main GuardType Hints and Runtime TypesRecap: Validate a Batch9Project: Order Processor
Project 1: Order ModelProject 2: Pricing PoliciesPractice on your own: Online Python compiler