Integer coercion and 2.2 Type/Class changes
Guido van Rossum
guido at python.org
Fri Oct 26 10:19:49 EDT 2001
com-nospam at ccraig.org (Christopher A. Craig) writes:
> Consider the following Python 2.2 code:
>
> >>> class foo(int):
> ... def __init__(self, n=0):
> ... self=n
This __init__ is a total no-op. The assignment to self is a local
variable rebinding that has no effect on the object that was initially
represented by self. In addition, since int is an immutable type, you
can't affect the value in __init__; you must use __new__ instead.
Your class works despite all that, because the default __new__
constructor does the right thing. :-)
> ... def bar(self): return self+6
> ...
> >>> t=foo(4)
> >>> t.bar()
> 10
> >>> type(t)
> <class '__main__.foo'>
> >>> type(t+6)
> <type 'int'>
> >>> type(t+t)
> <type 'int'>
>
> This is the expected result, but probably often not the desired one.
> So my question is, is there some way, without redefining all of
> the numeric operations, to define a subclass that recasts all numeric
> operations to it's own type?
No, you'll have to redefine all operators.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list