這是一個不同的答案,因爲它與我發佈的另一個截然不同。 (我覺得這理應是單獨的)
的代碼:
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