Structs to Instances
Lesson 32 of 48 in Coddy's Python for Rust Developers course.
Rust structs declare their fields and use impl blocks for behavior. A basic Python class can start empty and ordinary instances can receive attributes at runtime. Class creation and instance creation are distinct: calling Parcel() creates an instance. Attribute access uses a dot. This flexibility does not imply every Python object permits arbitrary attributes; classes with slots and many built-in types restrict them. Prefer initializing expected state consistently rather than relying on scattered later assignments.
Rust excerpt inside main
struct Parcel { label: String, weight: i32 }
let parcel = Parcel { label: String::from("sample"), weight: 4 };
println!("{}", parcel.label);
assert_eq!(parcel.weight, 4);Python
class Parcel:
pass
parcel = Parcel()
parcel.label = "sample"
parcel.weight = 4
print(parcel.label)Porting trap
Rust field visibility is compiler-enforced. Python a leading underscore convention asks callers to treat an attribute as internal, but does not enforce module privacy.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking7Instances and Shared State
Structs to InstancesInitialization and Ownershipself and Bound MethodsClass and Instance StateProperties and DisplayRecap: Model a Bank Account2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler