类装饰器,尤其是在 Python 2.6 及更高版本中,是包装许多方法以“返回此类类型的实例而不是超类的实例”的最便捷方式,正如其他人所指出的那样,这是您的潜在问题(除了__str__
对 vs的吹毛求疵之外__repr__
,值得但对您的问题根本没有解决办法;-)。
def returnthisclassfrom(specials):
specialnames = ['__%s__' % s for s in specials.split()]
def wrapit(cls, method):
return lambda *a: cls(method(*a))
def dowrap(cls):
for n in specialnames:
method = getattr(cls, n)
setattr(cls, n, wrapit(cls, method))
return cls
return dowrap
@returnthisclassfrom('and or xor')
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
a = Hex(2345)
b = Hex(5432)
print a, b, a^b
在 Python 2.6 中,这会发出
0x929 0x1538 0x1c11
如预期的。当然你可以给装饰器添加更多的方法名等等;如果您坚持使用 Python 2.5,请删除装饰线(以 开头的那条@
)并改用
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
Hex = returnthisclassfrom('and or xor')(Hex)
有点不那么优雅,但同样有效;-)
编辑:修复了代码中“通常的范围问题”的发生。