Menu
CoddyTech

Initializing Instance State

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

A Python initializer receives self and assigns instance attributes. It must return None, normally by reaching its end without a return. R constructor helpers often build and return a structured list or environment explicitly; that is a different contract from Python __init__. An environment can provide reference semantics for an R object, while a list-based object usually presents value-like updates. Create fresh lists inside each Python initializer when state must be independent. A local variable in __init__ disappears with the call unless retained elsewhere; self.attribute stores state on the object. Constructor defaults follow normal Python default-evaluation rules.

R

make_counter <- function(value=0) {
  e <- new.env(parent=emptyenv())
  e$value <- value
  e
}
a <- make_counter(5)
b <- make_counter()
cat(a$value, b$value, "\n")

Python

class Counter:
    def __init__(self, value=0):
        self.value = value
a = Counter(5)
b = Counter()
print(a.value, b.value)

Porting trap

Do not return a completed object from Python __init__ as you would from an R constructor helper. The Python construction machinery already has the instance.

challenge icon

Challenge

Beginner

Implement Scoreboard(name, points=0) with instance attributes name and points. Input is a name, an integer initial score, and an integer bonus on separate lines. The driver constructs one named board with that score and another named guest using the default, adds the bonus to the first, and prints name:points for each. Scores and bonuses may be negative. Initialization must store the supplied values independently.

The locked driver reads input and prints results. Submit the required class and function definitions only; do not read input or print in your solution. Keep the API names exactly as specified.

Your code goes in the editable files scoreboard.py. driver.py holds the supplied input/output code and API checks and cannot be edited. Keep the supplied imports; do not read input or print from the editable 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 R Developers

Practice on your own: Online Python compiler