Skip to content

Instantly share code, notes, and snippets.

@Xorcerer
Created May 13, 2014 07:07
Show Gist options
  • Save Xorcerer/9c229fcbcc6a7ea4fcd5 to your computer and use it in GitHub Desktop.
Save Xorcerer/9c229fcbcc6a7ea4fcd5 to your computer and use it in GitHub Desktop.
class NonNegativeDescriptor(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, type_):
return obj.data.get(self.name, 0)
def __set__(self, obj, value):
if value < 0:
value = 0
obj.data[self.name] = value
class Player(object):
def __init__(self):
self.data = {}
hp = NonNegativeDescriptor('hp')
mp = NonNegativeDescriptor('mp')
if __name__ == '__main__':
p = Player()
p.hp = 10
p.mp = -1
print (p.hp, p.mp) # (10, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment