python描述器(1)

先看一段代码,这段代码来自《流畅的python》 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 class Quantity: def __init__(self, storage_name): self.storage_name =storage_name def __set__(self, instance, value): if value > 0: # setattr(instance, self.storage_name, value) instance.__dict__[self.storage_name] = value else: raise ValueError('value must be > 0') def __get__(self, instance, owner): return getattr(instance, self.storage_name) class LineItem: weight1 = Quantity('weight') price1 = Quantity('price') def __init__(self, description, weight, price): self....

April 6, 2020 · 1 min · 148 words · Me