[Python-Dev] Semantics of __int__(), __index__()

Georg Brandl g.brandl at gmx.net
Thu Apr 4 16:59:24 CEST 2013

Am 04.04.2013 16:47, schrieb Chris Angelico:
> On Fri, Apr 5, 2013 at 1:23 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> The reason for calling int(obj) is to get an object that is precisely
>> of type int. When I call this I do not want any modified or additional
>> methods or data attached to the resulting object.
> There's something I'm fundamentally not understanding about this
> debate, and that is: How is it that calling a class can logically
> return anything other than an instance of that class? Taking it to a
> user-defined type:
> class Foo:
>     pass
> class Bar(Foo):
>     pass
> Is there any argument that I can pass to Foo() to get back a Bar()?
> Would anyone expect there to be one? Sure, I could override __new__ to
> do stupid things, but in terms of logical expectations, I'd expect
> that Foo(x) will return a Foo object, not a Bar object. Why should int
> be any different? What have I missed here?

I think the issue that the constructors for basic classes like int() are
often seen as built-in functions that "cast" values to the respective
type (or alternatively, functions that call the respective __method__
on the argument, like len()), not class constructors.

FWIW, I agree with you that the "class constructor" view is the right one
and would prefer exact int/str/... instances returned.


More information about the Python-Dev mailing list