This is a different answer because it is very different from the other that I posted. (and I felt it deserved to be separate)
The code:
class RandomInt: def __getattr__(self, name): attr = getattr(int, name, '') if attr != '': def wrapper(*args, **kw): return attr(random.randint(1, 100), *args, **kw) return wrapper else: raise AttributeError( "'{0}' object has no attribute '{1}'".format('RandomInt',name))
Example:
>>> x = RandomInt() >>> x 88 >>> 1 + x
There are opportunities for improvement:
>>> x + x Traceback (most recent call last): File "<pyshell#1456>", line 1, in <module> x + x TypeError: unsupported operand type(s) for +: 'instance' and 'instance'
Same for x*x , x/x and similar
Another version this time, similar to @gatto :
import random, inspect class RandomInt: def __init__(self): def inject(attr): def wrapper(*args, **kw): args = list(args) for i,x in enumerate(args): if isinstance(x, RandomInt): args[i] = x+0 return attr(random.randint(1,100), *args, **kw) return wrapper for name in dir(int): attr = getattr(int, name) if inspect.ismethoddescriptor(attr): setattr(self, name, inject(attr))
And it has support for:
>>> x + x 49 >>> x // x 2 >>> x * x 4958 >>> x - x 77 >>> x ** x 467056167777397914441056671494001L >>> float(x) / float(x) 0.28
Another version using class attributes to overcome the new style / old style problem (thanks @gatto):
import random, inspect class RandomInt(object): pass def inject(attr): def wrapper(*args, **kw): args = list(args) for i,x in enumerate(args): if isinstance(x, RandomInt): args[i] = random.randint(1,100) return attr(*args, **kw) return wrapper for name in dir(int): attr = getattr(int, name) if inspect.ismethoddescriptor(attr): setattr(RandomInt, name, inject(attr))
Output:
>>> x 86 >>> x 22 >>> x * x 5280 >>> [1] * x [1, 1, 1, 1, 1, 1] >>> x * '0123' '0123012301230123' >>> s[x]