[Python-Dev] Semantics of __int__(), __index__()
Guido van Rossum
guido at python.org
Wed Apr 3 18:36:50 CEST 2013
I always intended for int() and str() to case subclasses to the built-in
base class, and I don't want to change that rule.
Consider a subclass of int() that overrides __repr__() and __str__() to
print something fancy (maybe it defaults to hex; maybe it's an enum :-). I
want to be able to say repr(int(x)) and get the standard decimal
representation. Same with strings. If int() or str() were allowed to return
a subclass instance, this wouldn't work, and I'd have to resort to
draconian measures. (Betcha the first few solutions you come up with don't
even work. :-)
There are plenty of other use cases where a trivial subclass of one of the
built-in types is used as some kind of "flag" -- e.g. maybe for values that
ought to be serialized differently, or to enable some kind of type checking
-- but it should always be possible to convert such values to the
underlying base class to remove the special treatment.
--Guido van Rossum (python.org/~guido
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-Dev