Tables to Class Instances
Lesson 32 of 48 in Coddy's Python for Lua Developers course.
Lua objects are often tables with fields and methods. Python defines classes and creates instances by calling the class. An ordinary instance can gain attributes dynamically, making simple record usage familiar to Lua programmers. Python attribute lookup is not dictionary indexing, however: d.name is not d["name"] for a plain dict. Class instances can also restrict attributes, for example through slots, so dynamic assignment is not a universal guarantee for every object.
Lua example
local parcel = {}
parcel.label = "sample"
parcel.weight = 4
print(parcel.label)Python
class Parcel:
pass
parcel = Parcel()
parcel.label = "sample"
parcel.weight = 4
print(parcel.label)Porting trap
Use explicit initialization for attributes the rest of the program expects, rather than assuming absent fields behave like Lua nil lookups.
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 Lua Developers
1From Lua to Python
Run Your First Python ProgramPrinting and TextNames and Local ScopeNumbers and ConversionSuites Instead of endRecap: Rewrite a Receipt4Iteration and Transformations
Numeric for to rangepairs, ipairs, and itemsLoop Control and SkipsComprehensions and SortingRecap: Build a Ranking7Classes Beyond Metatables
Tables to Class InstancesConstructors and Fresh StateColon Calls to Bound MethodsLookup and Shared DefaultsProperties and tostringRecap: Model a Bank Account2Values and Decisions
nil Versus NoneTable Identity and EqualityTruthiness Is Differentelif and Value SelectionRecap: Eligibility Rules3Tables to Typed Collections
Sequence Tables to ListsTuples and Multiple ReturnsRecords to DictionariesSets and Shared TablesRecap: Clean an Inventory6Errors and Modules
Input and Exact Textpcall to Exceptionsrequire to importHints and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler