Menu
CoddyTech

Class State Is Not a Field

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

Choose the owner of state. An attribute assigned in a Python class body belongs to the class and can be found through instances. A fresh list assigned to self.items in __init__ belongs to that instance. Java static fields are a useful comparison for shared state, but Python instance assignment can shadow an ordinary class attribute: a.category changes that instance's lookup without changing Bag.category. In Java, accessing a static field through an instance expression still denotes the class field.

Java excerpt: class member declarations

// Class member
static class Bag {
    static String category = "tools";
    final java.util.List<String> items = new java.util.ArrayList<>();
}

Python

class Bag:
    category = "tools"
    def __init__(self):
        self.items = []
a, b = Bag(), Bag()
a.category = "books"
print(a.category, b.category, Bag.category)

Watch the difference

A class-body items = [] creates one shared list. Calling a.items.append changes that shared list if the instance has no own items attribute. Rebinding a.items and mutating a.items are therefore different operations.

Practice

Apply this comparison in the task below. Editable files: playlist.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

Implement Playlist with class attribute category = "music", a new tracks list per instance, and add(track) appending a string. The driver reads two possibly empty space-separated track lists and a category, fills two playlists, and reassigns category on the first instance only. It prints each category:comma-joined-tracks, then Playlist.category. Track names contain no commas or spaces. Python instance shadowing differs from assigning a Java static field through an instance.

Editable files: playlist.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 playlist import Playlist

a, b = Playlist(), Playlist()
for track in input().split():
    a.add(track)
for track in input().split():
    b.add(track)
a.category = input()
print(f"{a.category}:{','.join(a.tracks)}")
print(f"{b.category}:{','.join(b.tracks)}")
print(Playlist.category)
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