Menu
CoddyTech

Classes and Attribute Access

Lesson 32 of 48 in Coddy's Python for Kotlin Developers course.

Kotlin and Python both instantiate a class with a call rather than new. Python ordinary objects can receive attributes dynamically; Kotlin normally requires properties to be declared in the class. An empty Python class uses pass. The class itself is also an object, distinct from each instance. Both languages use a dot for member access, but Python generally discovers valid attributes at runtime.

Kotlin

class Parcel { var label = "" }
fun main() {
    val p = Parcel()
    p.label = "sample"
    println(p.label)
}

Python

class Parcel:
    pass
p = Parcel()
p.label = "sample"
print(p.label)

Porting trap

Do not assume the compiler will catch a misspelled Python attribute. Define intended instance state consistently, preferably during initialization.

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

challenge icon

Challenge

Beginner

Define an empty Parcel class using pass as its class body. Define make_parcel(label, weight) to create a fresh Parcel(), assign instance attributes label and weight, and return it. Input has five lines: first label, first integer weight, second label, second integer weight, and an integer increase. Labels may be empty; weights and increase are nonnegative. The driver increases only the first parcel's weight, then prints each parcel as label:weight, followed by whether the two parcels are identical (True or False).

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 parcel.py and functions.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 parcel import Parcel
from functions import make_parcel

a = make_parcel(input(), int(input()))
b = make_parcel(input(), int(input()))
assert isinstance(a, Parcel) and isinstance(b, Parcel)
a.weight += int(input())
print(f"{a.label}:{a.weight}")
print(f"{b.label}:{b.weight}")
print(a is b)
quiz iconTest yourself

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

All lessons in Python for Kotlin Developers

Practice on your own: Online Python compiler