Skip to content

Instantly share code, notes, and snippets.

@simplyvikram
Last active August 29, 2015 13:56
Show Gist options
  • Save simplyvikram/8851546 to your computer and use it in GitHub Desktop.
Save simplyvikram/8851546 to your computer and use it in GitHub Desktop.
Descriptors, __getattr__
# http://nbviewer.ipython.org/urls/gist.github.com/ChrisBeaumont/5758381/raw/descriptor_writeup.ipynb
# http://pyvideo.org/video/1760/encapsulation-with-descriptors
class NonNegativeValue(object):
__counter = 0
def __init__(self):
prefix = self.__class__.__name__
key = self.__class__.__counter
self.target_name = "_{0}_{1}".format(prefix, str(key))
self.__class__.__counter += 1
print 'Target name', self.target_name
def __get__(self, instance, owner):
return getattr(instance, self.target_name)
def __set__(self, instance, value):
if value <= 0:
raise ValueError('value must be > 0')
setattr(instance, self.target_name, value)
class LineItem(object):
weight = NonNegativeValue()
price = NonNegativeValue()
print "inside lineitem "
def __init__(self, description, weight, price):
self.description = description
self.weight = weight
self.price = price
def __getattr__(self, item):
print '__getattr__ called on self with item {0}'.format(item)
if item == 'blah':
return self.__dict__.get(item, 'default_blah')
raise AttributeError("{0} has no attribute {1}").format(
self.__class__.__name__, item
)
def __setattr__(self, key, value):
print '__setattr__ called on self with key:{0}, value:{1}'.format(
str(key), str(value)
)
# http://docs.python.org/2/reference/datamodel.html#implementing-descriptors
# self.__dict__[key] = value
super(LineItem, self).__setattr__(key, value)
def subtotal(self):
return self.weight * self.price
rice = LineItem('rice', 3, 5.65)
milk = LineItem('milk', 2, 4.50)
almonds = LineItem('almonds', 10, 14.95)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment