Last active
May 17, 2022 10:24
-
-
Save travishen/b31592d8558bfd119dfa6e2767743269 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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