Initialization and Fresh State
Lesson 33 of 48 in Coddy's Python for Go Developers course.
Go New-style constructor functions are a convention: struct literals and zero values remain possible. Python invokes __init__ after allocating an ordinary instance through the class call. Initialize instance attributes through self and do not return a value from __init__. Defaults can express an optional starting score. Each call below stores its own points attribute. Python does not automatically give an undeclared instance attribute a zero value.
Go
Go excerpt: declarations above main, statements inside main. Imports: fmt. The verification bundle contains the complete program.
type Board struct { Name string; Points int }
func NewBoard(name string) *Board { return &Board{Name: name} }
// Inside main:
a := NewBoard("red")
b := NewBoard("blue")
a.Points = 5
fmt.Println(a.Points, b.Points)Python
class Board:
def __init__(self, name, points=0):
self.name = name
self.points = points
a = Board("red")
b = Board("blue")
a.points = 5
print(a.points, b.points)Porting trap
If you access a missing Python attribute, you get AttributeError. If each instance needs a collection, create it in __init__ instead of putting one mutable collection on the class.
Challenge
BeginnerImplement 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. Go often uses a New-style function for defaults; here the Python initializer has a default points parameter.
Editable files: scoreboard.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
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.
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 Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking7Structs to Python Classes
From Structs to InstancesInitialization and Fresh StateReceivers and Bound MethodsClass State and ShadowingProperties and Display HooksRecap: Account State2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler