Usefulness of subclassing builtin number types
Antonio Cuni
TOGLIMIcuni at programmazione.it
Mon Dec 16 19:19:33 EST 2002
Gerhard Häring wrote:
> I want 'x' to stay of the class MyInt. I even can't think of any use
> case right now where I'd *not* want this. The problem? Python doesn't
> do this, instead it always returns ints.
what about the following?
def make_wrapper(method_name):
def wrapper(self, other):
return MyInt(getattr(int, method_name)(self, other))
return wrapper
class MetaInt(type):
methods = ['__add__', '__sub__']
def __new__(cls, bases, name, dic):
for method in MetaInt.methods:
dic[method] = make_wrapper(method)
return super(MetaInt, cls).__new__(cls, bases, name, dic)
class MyInt(int):
__metaclass__ = MetaInt
if __name__=='__main__':
x = MyInt(3)
y = x + 4
print y, type(y)
It seems to work, but I didn't test it very much: obviously it can be
improved, e.g. by giving 'int' and 'MyInt' as parameters instead of
hard-coded classes.
ciao Anto
--
"Computer science is not about computers any more than astronomy
is about telescopes." -- EW Dijkstra
More information about the Python-list
mailing list