Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 0.68 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Create per-instance property descriptor?
  2. class MyClass(object):
  3.   def __init__(self, **kwargs):
  4.     for attr, val in kwargs.items():
  5.       self.__dict__[attr] = MyDescriptor(val)
  6.        
  7. tv = MyClass(type="tv", size="30")
  8. smartphone = MyClass(type="phone", os="android")
  9.  
  10. tv.size   # do something smart with the descriptor
  11.        
  12. <property at 0x4067cf0>
  13.        
  14. class Descriptor:
  15.  
  16.     def __get__(...):
  17.         # this is called when the value is got
  18.  
  19.     def __set__(...
  20.     def __del__(...
  21.        
  22. obj.attr
  23. => type(obj).__getattribute__(obj, 'attr') is called
  24. => obj.__dict__['attr'] is returned if there else:
  25. => type(obj).__dict__['attr'] is looked up
  26. if this contains a descriptor object then this is used.