Menu
CoddyTech

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 icon

Challenge

Beginner

Implement 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}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Go Developers

Practice on your own: Online Python compiler