这是一个不同的答案,因为它与我发布的另一个截然不同。 (我觉得这理应是单独的)
的代码:
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))
一个实例运行:
>>> x = RandomInt()
>>> x
88
>>> 1 + x # __radd__
67
>>> x*100 # __mul__
1900
>>> x+5 # __add__
50
>>> x-1000 # __sub__
-945
>>> x//5 # __floordiv__
8
>>> float(x) # __float__
63.0
>>> str(x) # __str__
'75'
>>> complex(x) # __complex__
(24+0j)
>>> sum([x]*10)
573
有改进的余地:
>>> 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'
相同对于x*x
,x/x
和类似
另一个版本的时候,类似于@gatto's答案:
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))
而这其中有支持:
>>> x + x
49
>>> x // x
2
>>> x * x
4958
>>> x - x
77
>>> x ** x
467056167777397914441056671494001L
>>> float(x)/float(x)
0.28
另一个版本中,使用类属性克服新式/旧式问题(谢谢@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))
输出:
>>> x
86
>>> x
22
>>> x * x
5280
>>> [1] * x
[1, 1, 1, 1, 1, 1]
>>> x * '0123'
''
>>> s[x] # s = '' * 10
'5'
你说的是动态定义每个功能(在功能列表中添加,MUL,减等)返回randint传递给每个方法?编辑:甚至没有要求它在问题中说明它 – jamylak 2013-04-27 14:20:08
@jamylak:类似的东西。只要最终结果是RandomInt的“值”对每种方法都是随机的。 – Blender 2013-04-27 14:23:03
@Blender:啊,用于*每个*方法。是的,那么你需要创建方法..只有当“int”是左侧操作数*或*时,如果左侧操作数本身没有为操作定义一个钩子,它才会起作用。 – 2013-04-27 14:36:16