Editor

Fix the Shared State Bug

Advanced · Fix the bug · from Python Descriptors: The Secret Behind @property and ORM Fields

From the lesson: Python Descriptors: The Secret Behind @property and ORM Fields

When you use @property in Python, something interesting happens behind the scenes. The attribute doesn't just sit there waiting to be read - it intercepts access and runs custom code. How does that work?

Read the lesson

This descriptor has a common bug - all instances share the same value! Fix it so each instance has its own independent value.

Expected output:

Alice
Bob
class NameField:
def __init__(self):
self.value = None # Bug: shared across all instances!
def __set_name__(self, owner, name):
self.name = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
return self.value
def __set__(self, obj, value):
self.value = value
class Person:
name = NameField()
a = Person()
b = Person()
a.name = 'Alice'
b.name = 'Bob'
print(a.name)
print(b.name)

More Descriptor exercises

All Python exercises · 50 practice problems · Metaprogramming quiz