SHARE
TWEET

Helper class to make dicts from other classes with recursion

DeaD_EyE Mar 20th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class DictIter:
  2.     def __iter__(self):
  3.         yield from sorted(self._iter())
  4.  
  5.     def _iter(self):
  6.         for k,v in self.__dict__.items():
  7.             if k.startswith('_'):
  8.                 continue
  9.             if isinstance(v, self.__class__.__bases__):
  10.                 yield k, dict(v)
  11.             else:
  12.                 yield k, v
  13.         for k, v in self.__class__.__dict__.items():
  14.             if isinstance(v, property):
  15.                 yield k, v.fget(self)
  16.  
  17.     @property
  18.     def dict(self):
  19.         return dict(self)
  20.  
  21.  
  22. class Base(DictIter):
  23.     pass
  24.  
  25.  
  26. class Motor(Base):
  27.     def __init__(self, mode, start, stop):
  28.         self.mode = mode
  29.         self.start = start
  30.         self.stop = stop
  31.  
  32.  
  33. class State(Base):
  34.     bitrates = {br: 37.5 * br for br in range(1, 5)}
  35.  
  36.     def __init__(self):
  37.         self.motor = Motor('sector', 0, 360)
  38.         self._bitrate = 4
  39.         self._resolution = self.bitrates[self._bitrate]
  40.  
  41.     @property
  42.     def bitrate(self):
  43.         return self._bitrate
  44.  
  45.     @bitrate.setter
  46.     def bitrate(self, value):
  47.         print(value)
  48.         self._bitrate = value
  49.  
  50.  
  51. s = State()
  52. dict(s)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top