Skip to content

Instantly share code, notes, and snippets.

@travishen
Last active May 17, 2022 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travishen/b31592d8558bfd119dfa6e2767743269 to your computer and use it in GitHub Desktop.
Save travishen/b31592d8558bfd119dfa6e2767743269 to your computer and use it in GitHub Desktop.
class Quantity:
__counter = 0
def __init__(self):
cls = self.__class__
self.storage_name = f'_{cls.__name__}#{cls.__counter}'
cls.__counter += 1
def __get__(self, instance, owner): # `owner` is the ref of the managed class
if instance is None:
# when access from managed class not managed instance, e.g. `CartItem.price`
# return descriptor instance is better
return self
return getattr(instance, self.storage_name)
def __set__(self, instance, val):
if val > 0:
setattr(instance, self.storage_name, val)
else:
raise ValueError()
class CartItem:
weight = Quantity()
price = Quantity()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment