Menu
CoddyTech

Init and Per-instance Lists

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

GDScript _init initializes a script instance; Python uses __init__ with explicit self. Python class-body assignments define class attributes, unlike ordinary GDScript member initializers that run for each instance. Allocate independent lists inside Python initialization. Constructor parameters do not automatically become attributes. Godot RefCounted models release references automatically; these examples avoid Node ownership and freeing concerns.

GDScript

extends SceneTree
class Bag extends RefCounted:
    var items = []
func _init():
    var a = Bag.new()
    var b = Bag.new()
    a.items.append("pen")
    prints(a.items.size(), b.items.size())
    quit()

Python

class Bag:
    def __init__(self):
        self.items = []
a = Bag()
b = Bag()
a.items.append("pen")
print(len(a.items), len(b.items))

Porting trap

Do not put a mutable Python list in the class body when each object needs its own state. A default list parameter also persists across calls; use None and allocate inside.

Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.

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 GDScript Developers

Practice on your own: Online Python compiler