A class decorator, especially in Python 2.6 and beyond, is the handiest way to wrap a lot of methods to "return an instance of this class's type rather than an instance of the superclass", which, as other have indicated, is your underlying issue (beyond quibbles with __str__
vs __repr__
, worthwhile but not at all resolutory for your problem;-).
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
In Python 2.6, this emits
0x929 0x1538 0x1c11
as desired. Of course you can add more methodnames to the decorator, etc; if you're stuck with Python 2.5, remove the decorating line (the one starting with @
) and use instead
class Hex(int):
def __repr__(self): return hex(self)
__str__ = __repr__
Hex = returnthisclassfrom('and or xor')(Hex)
a mite less elegant, but just as effective;-)
Edit: fixed an occurence of "the usual scoping issue" in the code.
hex()
? docs.python.org/library/functions.html#hex – Assegai