Menu
CoddyTech

Instances Without new

Lesson 32 of 48 in Coddy's Python for Java Developers course.

Create an instance by calling a Python class, without new. A plain class with pass supplies an empty body; these ordinary instances can receive attributes after creation. Java fields are declared in the class, while this Python example creates attributes through assignment. An attribute that has never been set raises AttributeError when read; it is not automatically zero or null. Each Parcel() call creates fresh state, while assigning another name to the same instance shares it. Constructor-based initialization follows in the next lesson.

Java excerpt: class member declarations

// Class member
static class Parcel { String label; int weight; }

Python

class Parcel:
    pass
parcel = Parcel()
parcel.label = "sample"
parcel.weight = 4
print(parcel.label)

Watch the difference

The exercise separates parcel.py and functions.py. The supplied from parcel import Parcel exposes the class to its factory. Keep imports; do not add input at module level. Dynamic attributes are a feature of these ordinary classes, not a promise about every Python type.

Practice

Apply this comparison in the task below. Editable files: parcel.py, functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

In parcel.py define an empty Parcel class with pass. In functions.py implement make_parcel(label, weight), creating a fresh Parcel, setting label and weight, and returning it. The driver reads two label/weight pairs and an increase (all weights and increases nonnegative; labels may be empty), increases only the first parcel, prints both label:weight lines, then prints their identity comparison. Java declares fields; these ordinary Python instances receive attributes through assignment.

Editable files: parcel.py, functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Java Developers

Practice on your own: Online Python compiler