Advertisement
Guest User

animal-kingdom-sample

a guest
Sep 21st, 2012
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. __hunts__ = '__hunts__'
  2. __hunted_by__ = '__huntedBy__'
  3.  
  4. class Animal(object):
  5.     def __init__(self):
  6.         self.__dict__ = {}
  7.        
  8.     def __repr__(self):
  9.         return self.className
  10.    
  11.     def __str__(self):
  12.         return self.className
  13.        
  14.     def __getattr__(self,key):
  15.         __key__ = '__%s__' % (key.replace('_',''))
  16.         return '%s.%s --> "%s"' % (self,key,', '.join([c.className for c in self.__dict__[__key__]])) if (self.__dict__.has_key(__key__)) else '%s.%s --> %s' % (self,key,None)
  17.    
  18.     def __hunts__(self,prey):
  19.         if (not self.__dict__.has_key(__hunts__)):
  20.             self.__dict__[__hunts__] = []
  21.         if (prey not in self.__dict__[__hunts__]):
  22.             self.__dict__[__hunts__].append(prey)
  23.         try:
  24.             if (not prey.__dict__.has_key(__hunted_by__)):
  25.                 prey.__dict__[__hunted_by__] = []
  26.             if (self not in prey.__dict__[__hunted_by__]):
  27.                 prey.__dict__[__hunted_by__].append(self)
  28.         except:
  29.             i = 0
  30.             while (i < len(self.__dict__[__hunts__])):
  31.                 if (self.__dict__[__hunts__][i] == prey):
  32.                     del self.__dict__[__hunts__][i]
  33.                     break
  34.                
  35.     def className():
  36.         doc = "className"
  37.         def fget(self):
  38.             return str(self.__class__).split()[-1].split("'")[1]
  39.         return locals()    
  40.     className = property(**className())
  41.  
  42.                    
  43. class Lion(Animal):
  44.     def __init__(self):
  45.         super(Animal, self).__init__()
  46.         self.__dict__['__class__'] = self.className
  47.        
  48. class Tiger(Animal):
  49.     def __init__(self):
  50.         super(Animal, self).__init__()
  51.         self.__dict__['__class__'] = self.className
  52.        
  53. _lion_ = Lion()
  54.  
  55. _tiger_ = Tiger()
  56.  
  57. _lion_.__hunts__(_tiger_)
  58.  
  59. print 'BEGIN:'
  60. print _lion_.hunts
  61. print _tiger_.hunts
  62.  
  63. print _lion_.huntedBy
  64. print _tiger_.huntedBy
  65. print 'END !'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement