Skip to content

Instantly share code, notes, and snippets.

@danilobellini
Created March 28, 2013 02:54
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 danilobellini/5260156 to your computer and use it in GitHub Desktop.
Save danilobellini/5260156 to your computer and use it in GitHub Desktop.
Descriptor use case example (based on Luciano Ramalho "Encapsulation with descriptors" video at PyCon 2013)
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 23:36:30 2013
Descriptor use case example
@author: Danilo J. S. Bellini
"""
class Quantity(object):
def __get__(self, instance, owner):
return getattr(instance, self.descr_name)
def __set__(self, instance, value):
if value < 0:
raise ValueError("Value should be non-negative")
setattr(instance, self.descr_name, value)
def initialize_quantities(cls):
for name, attr in cls.__dict__.iteritems():
if isinstance(attr, Quantity):
attr.descr_name = "__" + name
return cls
@initialize_quantities
class Item(object):
value = Quantity()
amount = Quantity()
def __init__(self, value, amount=1):
self.amount = amount
self.value = value
@property # Just to avoid unintended assignment
def total_value(self):
return self.value * self.amount
# Example:
items = [Item(5, 2), Item(3, 7)]
for it in items:
print it.value, it.amount, it.total_value
print it.__dict__
# Output:
# 5 2 10
# {'__value': 5, '__amount': 2}
# 3 7 21
# {'__value': 3, '__amount': 7}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment