Constructors and Fresh State
Lesson 33 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin primary constructors and property initializers set up each instance. Python uses __init__ with an explicit self parameter to initialize an already created instance. Put independent lists on self inside __init__; a list in the Python class body belongs to the class and is shared through lookup. Constructor parameters are not automatically stored as Python attributes, unlike Kotlin val/var constructor properties.
Kotlin
class Bag { val items = mutableListOf<String>() }
fun main() {
val a = Bag(); val b = Bag()
a.items.add("pen")
println("${a.items.size} ${b.items.size}")
}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
Python __init__ must not return a replacement object. Store a parameter with self.name = name; merely accepting name does not create that attribute.
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 Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking7Instances and Shared State
Classes and Attribute AccessConstructors and Fresh StateReceivers and Bound MethodsCompanions and Class StateProperty Accessors and TextRecap: Model a Bank Account2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler