metaprogramming examples
This commit is contained in:
@@ -45,23 +45,23 @@ class Quantity:
|
||||
|
||||
def __init__(self):
|
||||
cls = self.__class__ # <2>
|
||||
prefix = cls.__name__ # <3>
|
||||
index = cls.__counter # <4>
|
||||
self.storage_name = '_{}_{}'.format(prefix, index) # <5>
|
||||
cls.__counter += 1 # <6>
|
||||
prefix = cls.__name__
|
||||
index = cls.__counter
|
||||
self.storage_name = '_{}_{}'.format(prefix, index) # <3>
|
||||
cls.__counter += 1 # <4>
|
||||
|
||||
def __get__(self, instance, owner): # <7>
|
||||
return getattr(instance, self.storage_name) # <8>
|
||||
def __get__(self, instance, owner): # <5>
|
||||
return getattr(instance, self.storage_name) # <6>
|
||||
|
||||
def __set__(self, instance, value): # <9>
|
||||
def __set__(self, instance, value):
|
||||
if value > 0:
|
||||
setattr(instance, self.storage_name, value) # <10>
|
||||
setattr(instance, self.storage_name, value) # <7>
|
||||
else:
|
||||
raise ValueError('value must be > 0')
|
||||
|
||||
|
||||
class LineItem:
|
||||
weight = Quantity() # <11>
|
||||
weight = Quantity() # <8>
|
||||
price = Quantity()
|
||||
|
||||
def __init__(self, description, weight, price):
|
||||
@@ -71,4 +71,4 @@ class LineItem:
|
||||
|
||||
def subtotal(self):
|
||||
return self.weight * self.price
|
||||
# END LINEITEM_V4
|
||||
# END LINEITEM_V4
|
||||
|
||||
Reference in New Issue
Block a user