Declared Fields and Attributes
Lesson 32 of 48 in Coddy's Python for Dart Developers course.
Dart classes declare fields and methods, and construction is checked against the class API. Ordinary Python instances usually permit attributes to be attached dynamically, unless the class restricts that behavior. A Python class call constructs an instance without a new keyword. An empty class body needs pass because a suite must contain a statement. A missing Python attribute raises AttributeError rather than being a declared uninitialized field. Two constructions produce separate objects, while assigning another name to an existing instance aliases it. Later lessons move initial state into __init__ so the object's expected fields are established consistently.
Dart
class Parcel {
String label = '';
}
void main() {
final parcel = Parcel();
parcel.label = 'sample';
print(parcel.label);
}Python
class Parcel:
pass
parcel = Parcel()
parcel.label = 'sample'
print(parcel.label)Porting trap
Do not assume every Python attribute has a declaration in the class body. Read the initializer and methods that assign instance state.
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 Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking7Objects and Shared State
Declared Fields and AttributesConstructors and __init__this and Bound MethodsClass Fields and LookupGetters, Setters, and __str__Recap: Model a Bank Account2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler