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
BeginnerImplement 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}")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking7Objects and Shared State
R Objects and Python ClassesInitializing Instance StateReceiver Methods and GenericsClass Lookup and Shared ListsValidated Attribute AccessRecap: Model a Bank Account2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler