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
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 GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking7Instances and Shared State
New and Python Class CallsInit and Per-instance ListsCallable and Bound MethodsStatic and Instance StateSetters and Printable ObjectsRecap: Model a Bank Account2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler