Few questions about new features in Python 2.2
Guido van Rossum
guido at python.org
Tue Oct 23 20:15:23 EDT 2001
s.keim at laposte.net (sebastien) writes:
> How to overload builtins constructor?
> -------------------------------------
> I have tried something like:
> class xxx (int):
> def __init__(self, x, y):
> int.__init__ (self, x*y)
> That doesn't seem to work.
Use __new__ instead of __init__ for immutable constructors. There are
tons of examples in Lib/test/test_descr.py. This particular one could
be written:
class I(int):
def __new__(cls, x, y):
return int.__new__(cls, x*y)
> What is the goal for __floordiv__ ?
> -----------------------------------
> I doesn't understand why to have appended this special method.
> For me with or without from __future__ import division, the new //
> operator could
> call the old __div__ method.
> Or there is a pitfall that I haven't seen?
Objects may define both / and // with different semantics (/ returning
a float and // returning a truncated int), so you need to be able to
overload two different operators. That's what __floordiv__ is for.
Because classic division might either map to / or to //, depending on
the type, you can overload all three separately: __div__ for classic
/, __floordiv__ for //, and __truediv__ for / under the future
statement. Typically, __div__ should be just an alias for either of
the others -- but Python can't know whether your object type is
int-like or float-like, so it can't know which one to choose.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list