【发布时间】:2011-01-08 22:26:27
【问题描述】:
我想做以下事情:
class A(object): pass
a = A()
a.__int__ = lambda self: 3
i = int(a)
不幸的是,这会引发:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'A'
这似乎只在我将“特殊”方法分配给类 A 而不是它的实例时才有效。有什么办法吗?
我想到的一种方法是:
def __int__(self):
# No infinite loop
if type(self).__int__.im_func != self.__int__.im_func:
return self.__int__()
raise NotImplementedError()
但这看起来相当难看。
谢谢。
【问题讨论】: