Bind Descriptor Names with __set_name__
Core idea
When type creates a class, it notifies class namespace objects that provide set_name(self, owner, name). A descriptor can use the assigned name to choose a distinct backing attribute. The hook runs for direct entries at class creation, not automatically for inheritance or later assignment. This lets one descriptor class manage multiple fields.
class Field: def __set_name__(self, owner, name): self.key = '_' + name def __get__(self, obj, owner): if obj is None: return self return getattr(obj, self.key) def __set__(self, obj, value): setattr(obj, self.key, value)class Package: width = Field() height = Field()p = Package()p.width, p.height = 4, 7print(p.width, p.height, sorted(vars(p)))Separate descriptor objects receive distinct names and store values under different keys.
Attach a field after creation
class Marker: def __set_name__(self, owner, name): self.label = owner.__name__ + '.' + nameclass Base: code = Marker()class Child(Base): passextra = Marker()Child.extra = extraprint(Base.code.label, Child.code.label)print(hasattr(extra, 'label'))extra.__set_name__(Child, 'extra')print(extra.label)Inherited objects keep their original binding. A late attachment requires explicit notification when needed.
Common mistake
Do not reuse the same stateful Field object for two names: the later notification can overwrite its stored key. Use separate instances.
Practice
Add a third field called depth to Package. Inspect its backing key and check that changing depth leaves width and height unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Set name
Check your understanding of set name.
What is printed?
class D: def __set_name__(self, owner, name): self.name=nameclass C: rate=D()print(C.rate.name)What is printed?
class D: def __set_name__(self, owner, name): self.owner=owner.__name__class A: x=D()class B(A): passprint(B.x.owner)When is __set_name__ automatically invoked?
What is safer for two independently named fields?