Descriptors and attribute lookup
A stock count must stay nonnegative whenever it is assigned. Use the same validation rule on more than one object without mixing their values.
On this page
Read the model
A descriptor lives on a class and participates in attribute access. Python calls its __set_name__ when creating the owner class. The descriptor below remembers a storage name. Each Stock instance owns the actual count.
Follow the example
class Count:
def __set_name__(self, owner, name):
self.key = "_" + name
def __get__(self, obj, owner=None):
return self if obj is None else vars(obj)[self.key]
def __set__(self, obj, value):
if type(value) is not int or value < 0:
raise ValueError("expected a nonnegative integer")
vars(obj)[self.key] = value
class Stock:
count = Count()
a, b = Stock(), Stock()
a.count, b.count = 3, 8
print(a.count, b.count)The first assignment calls set with a as obj and 3 as value. The descriptor writes into a’s dictionary. Reading a.count calls get on the same descriptor but supplies a as the instance. The two reads therefore print 3 8. Reading Stock.count supplies no instance and returns the descriptor itself.
Change one condition
After the two assignments, try setting a.count to -1. Catch ValueError and print a.count again. It is still 3 because validation runs before the write. If the descriptor stored the count on self instead of obj, the second assignment would overwrite the first object’s value.