Structs and Dynamic Attributes
Lesson 32 of 48 in Coddy's Python for Swift Developers course.
Swift structs and classes declare stored properties. Python classes can create ordinary instances with dynamically assigned attributes. Call the class to create an instance; no new keyword is used. A basic empty class allows adding label and weight later, although many built-in objects and classes with slots restrict attributes. Missing normal attributes raise AttributeError instead of yielding an optional. Prefer consistent initialization for state the class requires.
Swift example
struct Parcel { var label: String; var weight: Int }
let parcel = Parcel(label: "sample", weight: 4)
print(parcel.label)Python
class Parcel:
pass
parcel = Parcel()
parcel.label = "sample"
parcel.weight = 4
print(parcel.label)Porting trap
Python does not provide Swift struct value semantics by default. Ordinary class instances are shared when assigned to another name.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
Challenge
BeginnerDefine 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Swift Developers
1From Swift to Python
Run Your First Python ProgramPrinting and Stringslet, var, and RebindingInt Range and DivisionIndentation and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for and Half-Open Rangesenumerated to enumeratewhile and Loop Controlmap, filter, ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs and Dynamic Attributesinit to __init__self and Method ReferencesType Properties and ShadowingComputed Properties and TextRecap: Model a Bank Account2Values and Decisions
Optionals and NoneEquatable and IdentityBool Conditions and FallbacksBranches and TernariesRecap: Eligibility Rules3Value Types to Shared Objects
Array to listTuples and UnpackingDictionary Lookup and OrderValue Copies and AliasesRecap: Clean an Inventory6Errors and Modules
Input and String Formattingthrows, defer, and withModules and Main GuardsHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler