这有点工作,但您可以包装它并创建一个委托人。实际上,我做了与您所做的类似的事情,以创建一个默认以十六进制打印的 int 。一个更好的例子来自我自己的一个子类 int 的类,以允许位切片读取(写入显然不起作用,因为 int 是不可变的,所以这个特定的代码并没有走远......)。一个例子可能有很多代码,但它显示了如何使用它:
# I stole this decorator from another stackoverflow recipe :)
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
def int_getslice(self, i, j):
# NON-pythonic, will return everything inclusive i.e. x[5:3] returns 3 bits, not 2.
# Because that's what users normally expect.
# If you're a purist, modify below.
if i > 1000000 or j > 1000000:
raise ValueError, 'BitSize limited to 1 million bits'
lo = min(i,j)
hi = max(i,j)
mask = (1<<((hi-lo)+1))-1
return (self>>lo) & mask
def int_getitem(self, i):
# Safety limit
if i > 1000000:
raise ValueError, 'BitSize limited to 1 million bits'
return (self>>i)&1
def int_iter(self):
# since getitem makes it iterable, override
raise AttributeError, 'int object is not iterable'
@returnthisclassfrom('abs add and div floordiv lshift mod mul neg or pow radd rand rdiv rdivmod rfloordiv rlshift rmod rmul ror rpow rrshift rshift rsub rxor rtruediv sub truediv xor trunc')
class BitSliceInt(long):
__getslice__ = int_getslice
__getitem__ = int_getitem
__iter__ = int_iter