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

Guido van Rossum guido at python.org
Thu Apr 4 16:59:49 CEST 2013

On Thu, Apr 4, 2013 at 7:47 AM, Chris Angelico <rosuav at gmail.com> wrote:

> 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?

A class can define a __new__ method that returns a different object. E.g.
(python 3):

>>> class C:
...   def __new__(cls): return 42
>>> C()

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20130404/504da284/attachment.html>

More information about the Python-Dev mailing list