Usefulness of subclassing builtin number types
Michele Simionato
mis6 at pitt.edu
Wed Dec 18 09:39:39 EST 2002
Antonio Cuni <TOGLIMIcuni at programmazione.it> wrote in message news:<miqlta.vh4.ln at anto.cuni.lan>...
> 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
Nice to see other Italians here ! Especially now that there a Big Absent ;-)
BTW, you probably mean __new__(cls,name,bases,dic) instead of
__new__(cls,bases,name,dic)
Michele
More information about the Python-list
mailing list