Python › Descriptors & Properties
How does __set_name__ let a descriptor automatically learn the attribute name it's being assigned to on the owning class?
IntermediateAnswer
__set_name__(self, owner, name) is automatically called by Python ONCE, at CLASS CREATION time, passing the owning class and the exact attribute name the descriptor was assigned to — letting a reusable descriptor derive a private storage attribute name (like '_price') without the user having to pass it explicitly.
class Validated:
def __set_name__(self, owner, name):
self.private_name = f"_{name}" # automatically learns its own name
def __get__(self, instance, owner):
return getattr(instance, self.private_name)
def __set__(self, instance, value):
setattr(instance, self.private_name, value)
class Product:
price = Validated() # __set_name__ automatically learns 'price' -> '_price'Real-world example Building a reusable descriptor class that automatically derives its own storage attribute name without manual configuration.