Objects and Public Attributes
Lesson 32 of 48 in Coddy's Python for Ruby Developers course.
Python and Ruby both build objects from classes, but their attribute access models differ. Ruby instance variables use an at-sign and are accessed inside methods; attr_accessor generates reader and writer methods for public use. Ordinary Python objects can receive attributes through dotted assignment, even after construction, unless their class restricts it. Python pass is an empty statement used where a suite is required. Python class definitions use a colon and indentation instead of Ruby end. Creating two objects constructs independent identities; assigning a second name to an existing instance only aliases it. Later lessons put initial state into constructors.
Ruby
class Parcel
attr_accessor :label
end
parcel = Parcel.new
parcel.label = 'sample'
puts parcel.labelPython
class Parcel:
pass
parcel = Parcel()
parcel.label = 'sample'
print(parcel.label)Porting trap
Do not paste Ruby @label into Python. Use self.label inside a method or an instance expression followed by .label outside it.
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 Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking7Objects and Shared State
Objects and Public Attributesinitialize and __init__Explicit self ParametersShared Class StateReaders, Writers, and strRecap: Model a Bank Account2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler