Advertisement
Guest User

Untitled

a guest
Apr 20th, 2014
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.09 KB | None | 0 0
  1. from abc import ABCMeta, abstractmethod
  2. import random
  3.  
  4. class BaseSource:
  5. __metaclass__ = ABCMeta
  6.  
  7. @abstractmethod
  8. def get(self):
  9. pass
  10.  
  11. class ManualSrc(BaseSource):
  12. def get(self):
  13. return float(raw_input('gimme a number - '))
  14.  
  15. class RandomSrc(BaseSource):
  16. def get(self):
  17. return random.random()
  18.  
  19. class Source(BaseSource):
  20. """generic Source choice"""
  21. def __new__(BaseSource, choice):
  22. if choice == 0:
  23. return ManualSrc()
  24. elif choice == 1:
  25. return RandomSrc()
  26. else:
  27. raise ValueError('source choice parameter {} not valid'.format(choice))
  28.  
  29. if __name__ == '__main__':
  30. for use_src in range(4):
  31. print 'using source choice {}'.format(use_src)
  32. src = Source(use_src)
  33. print src.get()
  34.  
  35. ## [ . . . ]
  36.  
  37. class RandomSrc(BaseSource):
  38. def get(self):
  39. return random.random()
  40.  
  41. def create_source(choice):
  42. if choice == 0:
  43. return ManualSrc()
  44. elif choice == 1:
  45. return RandomSrc()
  46. else:
  47. raise ValueError('source choice parameter {} not valid'.format(choice))
  48.  
  49. if __name__ == '__main__':
  50. for use_src in range(4):
  51. print 'using source choice {}'.format(use_src)
  52. src = create_source(use_src)
  53. print src.get()
  54.  
  55. ## [ . . . ]
  56.  
  57. class RandomSrc(BaseSource):
  58. def get(self):
  59. return random.random()
  60.  
  61. class WhateverSrc(BaseSource):
  62. def get(self):
  63. return "Foo Bar??"
  64.  
  65. def create_source(choice):
  66. if choice == 0:
  67. return ManualSrc()
  68. elif choice == 1:
  69. return RandomSrc()
  70. elif choice == 2:
  71. return WhateverSrc()
  72. else:
  73. raise ValueError('source choice parameter {} not valid'.format(choice))
  74.  
  75. import random
  76.  
  77. class ManualSrc(object):
  78. def get(self):
  79. return float(raw_input('gimme a number - '))
  80.  
  81. class RandomSrc(object):
  82. def get(self):
  83. return random.random()
  84.  
  85. class BreakingSrc(object):
  86. pass
  87.  
  88. def create_source(choice):
  89. if choice == 0:
  90. return ManualSrc()
  91. elif choice == 1:
  92. return RandomSrc()
  93. elif choice == 2:
  94. return BreakingSrc()
  95. else:
  96. raise ValueError('source choice parameter {} not valid'.format(choice))
  97.  
  98. if __name__ == '__main__':
  99. for use_src in range(4):
  100. print 'using source choice {}'.format(use_src)
  101. src = create_source(use_src)
  102. print src.get()
  103.  
  104. using source choice 0
  105. gimme a number - 1
  106. 1.0
  107. using source choice 1
  108. 0.702223268052
  109. using source choice 2
  110. Traceback (most recent call last):
  111. File "./stack26.py", line 28, in <module>
  112. print src.get()
  113. AttributeError: 'BreakingSrc' object has no attribute 'get'
  114.  
  115. from abc import ABCMeta, abstractmethod
  116. import random
  117. import inspect
  118.  
  119. available_srcs = []
  120.  
  121. def register(newclass):
  122. if inspect.isabstract(newclass):
  123. print ("newclass %s is abstract, and has abstract"
  124. " methods: %s. Refusing to register"
  125. % (newclass, newclass.__abstractmethods__))
  126. return
  127. if newclass not in available_srcs:
  128. available_srcs.append(newclass)
  129. print "Registered %s as available source" % newclass
  130.  
  131. class MyMetaClass(ABCMeta):
  132. def __new__(cls, clsname, bases, attrs):
  133. newclass = super(MyMetaClass, cls).__new__(cls, clsname, bases, attrs)
  134. register(newclass) # here is your register function
  135. return newclass
  136.  
  137. class BaseSource(object):
  138. __metaclass__ = MyMetaClass
  139.  
  140. @abstractmethod
  141. def get(self):
  142. pass
  143.  
  144. class ManualSrc(BaseSource):
  145. def get(self):
  146. return float(raw_input('gimme a number - '))
  147.  
  148. class RandomSrc(BaseSource):
  149. def get(self):
  150. return random.random()
  151.  
  152. if __name__ == '__main__':
  153. for use_src in range(4):
  154. print 'using source choice {}'.format(use_src)
  155. src = available_srcs[use_src]()
  156. print src.get()
  157.  
  158. >>> import logging
  159. >>> log = logging.getLogger('hello')
  160. >>> vars(log)
  161. {'name': 'hello', 'parent': <logging.RootLogger object at 0x17ce850>, 'handlers': [], 'level': 0, 'disabled': 0, 'manager': <logging.Manager object at 0x17ce910>, 'propagate': 1, 'filters': []}
  162. >>> type(log)
  163. <class 'logging.Logger'>
  164.  
  165. a = A()
  166. a.x = 5
  167. print "a.x is %s" % a.x
  168.  
  169. class B(object):
  170. def __init__(self):
  171. self.x = 10
  172. @property
  173. def x(self):
  174. return "I ain't returning x but something weird, and x is %s... FYI"
  175. % self._x
  176. @x.setter
  177. def x(self, x):
  178. self._x = int(self._x if hasattr(self, '_x') else 0 + 2 * x)
  179.  
  180. def A():
  181. return B()
  182.  
  183. >>> class C(object):
  184. ... pass
  185. ...
  186. >>> vars(C)
  187. dict_proxy({'__dict__': <attribute '__dict__' of 'C' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None})
  188. >>> type(C)
  189. <type 'type'>
  190. >>> def get_me_a_c_class():
  191. ... return C
  192. ...
  193. >>> my_class = get_me_a_c_class()
  194. >>> my_instance = my_class()
  195. >>> type(my_instance)
  196. <class '__main__.C'>
  197. >>> type(get_me_a_c_class)
  198. <type 'function'>
  199. >>> vars(get_me_a_c_class)
  200. {}
  201. >>> get_me_a_c_class.random_attribute = 5
  202. >>> print "Did I just put an attribute to a FUNCTION??: %s" % get_me_a_c_class.random_attribute
  203. Did I just put an attribute to a FUNCTION??: 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement