Advertisement
Woobinda

Расширение типов, магические методы

Dec 24th, 2015
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. """
  2. Класс, реализующий расширение типов "встраиванием"
  3. """
  4.  
  5. class Set:
  6.     def __init__(self, value = []):
  7.         self.data = []
  8.         self.concat(value)
  9.  
  10.     def intersect(self, other):
  11.         res = []
  12.         for x in self.data:
  13.             if x in other:
  14.                 res.append(x)
  15.         return Set(res)
  16.  
  17.     def union(self, other):
  18.         res = self.data[:]
  19.         for x in other:
  20.             if not x in res:
  21.                 res.append(x)
  22.         return Set(res)
  23.  
  24.     def concat(self, value):
  25.         for x in value:
  26.             if not x in self.data:
  27.                 self.data.append(x)
  28.  
  29.     def __len__(self):
  30.         return len(self.data)
  31.  
  32.     def __getitem__(self, key):
  33.         return self.data[key]
  34.  
  35.     def __and__(self, other):
  36.         return self.intersect(other)
  37.  
  38.     def __or__(self, other):
  39.         return self.union(other)
  40.  
  41.     def __repr__(self):
  42.         return 'Set:' + repr(self.data)
  43.  
  44.  
  45.  
  46. """
  47. Подкласс, реализующий передачу методам & и | любого количества аргументов
  48. """
  49.  
  50. class Sub(Set):            
  51.     def intersect(self, *others):
  52.         result = []
  53.         for arg in self.data:
  54.             for other in others:
  55.                 if arg not in other: break
  56.             else:
  57.                 result.append(arg)
  58.         return Set(result)
  59.    
  60.     def union(self, *others):
  61.         result = self.data[:]
  62.         for value in others:
  63.             for arg in value:
  64.                 if not arg in result:
  65.                     result.append(arg)
  66.         return Set(result)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement