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
BeginnerImplement 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)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking7Instance and Class State
Instances Without newInitializing Instance StateBound Methods and selfClass State Is Not a FieldProperties and Access ControlRecap: Account State2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler