Advertisement
Guest User

Untitled

a guest
Aug 19th, 2013
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. import numbers
  2. import operator
  3. import random
  4.  
  5. class RandomInt(object):
  6.     def __init__(self, a, b):
  7.         self.a, self.b = a, b
  8.     def __int__(self):
  9.         return random.randint(self.a, self.b)
  10.     def __float__(self):
  11.         return float(int(self))
  12.     def __repr__(self):
  13.         return repr(int(self))
  14.     def __hash__(self):
  15.         raise NotImplemented
  16.  
  17. for op in ('add', 'sub', 'mul', 'truediv', 'floordiv',
  18.            'mod', 'divmod', 'pow', 'lshift', 'rshift',
  19.            'and_', 'xor_', 'or_'):
  20.     def foo(self, rhs, op=op):
  21.         return getattr(operator, op)(int(self), rhs)
  22.     def rfoo(self, lhs, op=op):
  23.         return getattr(operator, op)(lhs, int(self))
  24.     setattr(RandomInt, '__' + op.rstrip('_') + '__', foo)
  25.     setattr(RandomInt, '__r' + op.rstrip('_') + '__', rfoo)
  26.  
  27. for op in 'neg', 'pos', 'abs', 'invert':
  28.     def foo(self, op=op):
  29.         return getattr(operator, op)(int(self))
  30.     setattr(RandomInt, '__' + op.rstrip('_') + '__', foo)
  31.  
  32. numbers.Integral.register(RandomInt)
  33.    
  34. a = RandomInt(4, 11)
  35. print(a)
  36. print(a + a)
  37. print(a + 3)
  38. print(3 + a)
  39. print(float(a))
  40. print(complex(a))
  41. print(round(a))
  42. print(repr(a))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement