Advertisement
DigitalMag

draft for django-enum

Apr 29th, 2019
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. class Enum (tuple):
  2.     __values = {}
  3.  
  4.     def __getattr__(self, attr):
  5.         if attr in self.values.values():
  6.             return 2**self.values.values().index(attr)
  7.         else:
  8.             raise Exception('called enum-object has no the attr called'
  9.                             +' \"'+attr+'\" and has no the value named \"'+attr+'\"')
  10.  
  11.     def __getitem__(self, key):
  12.         if key in self.values.keys():
  13.             return self.values[key]
  14.         else:
  15.             return self.__getattr__(key)
  16.  
  17.     def __iter__(self):
  18.         for item in self.values.items():
  19.             yield item
  20.  
  21.     def __new__(cls, *iterable):                                                  # итератор двойных итераторов
  22.         id=1
  23.  
  24.         for it in iterable:
  25.             Enum.__values[id]=it
  26.             id <<= 1
  27.  
  28.         return tuple.__new__(cls, Enum.__values.keys())
  29.  
  30.     def __init__(self, *keys):                                                   # итератор двойных итераторов
  31.         self.values = Enum.__values.copy()
  32.         Enum.__values = {}
  33.         super(Enum, self).__init__(keys)
  34.  
  35.     def __str__(self):
  36.         return super(Enum, self).__repr__()
  37.  
  38.     def __repr__(self):
  39.         r = 0
  40.         for i in self.values:
  41.             r |= i
  42.         return str(r)
  43.  
  44. def main():
  45.     e = Enum('first','dfdf','rt')
  46.     print e[1]
  47.     print e
  48.  
  49.     print ''
  50.  
  51.     for i in e:
  52.         print i
  53.  
  54.     print ''
  55.  
  56.     s = Enum('second')
  57.     print s[1]
  58.     print e['first']
  59.     print e.first
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement