R Objects and Python Classes
Lesson 32 of 48 in Coddy's Python for R Developers course.
R supports several object systems rather than one universal class declaration model. S3 often attaches a class attribute to an ordinary value, S4 defines formal classes, and reference-oriented systems support mutable encapsulated objects. Python ordinary classes define constructors, methods, and attribute lookup directly. An ordinary Python instance can receive a new attribute by dotted assignment unless restricted by its class. A class body must contain a statement, so pass supplies an empty body. Two class calls create distinct objects; assigning another name to one instance shares it. Do not infer Python object behavior solely from an R list with a class attribute.
R
parcel <- structure(list(label="sample"), class="parcel")
cat(parcel$label, "\n", sep="")
cat(class(parcel), "\n", sep="")Python
class Parcel:
pass
parcel = Parcel()
parcel.label = 'sample'
print(parcel.label)Porting trap
An R class label can drive generic dispatch without declaring a Python-style class. Port the intended behavior, not merely the label.
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 R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking7Objects and Shared State
R Objects and Python ClassesInitializing Instance StateReceiver Methods and GenericsClass Lookup and Shared ListsValidated Attribute AccessRecap: Model a Bank Account2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler