On Sun, Oct 28, 2018 at 12:53 PM Joy Diamond <python....@gmail.com> wrote:
>> - type(x) and x.__class__ don't necessarily agree; under what
>>   circumstances are each used?
>>
>> (I've asked this before, and either never got a good answer, or I can't
>> keep it straight in my head.)
>>
>> - what precisely does type(x) do?
>
>
> 1.  `type(x)` gets the true actual type of `x`.
> 2.  `x.__class__` gets the `.__class__` attribute for `x`, which by default 
> gets the actual true type of `x`, but may be replace by the user to do other 
> stuff.
>

Not that simple.

>>> class X:
...   cls = "X"
...
>>> class Y:
...   cls = "Y"
...
>>> x = X()
>>> x.__class__ = Y
>>> x.cls
'Y'
>>> type(x)
<class '__main__.Y'>

I don't know what the "true actual type" is, since I just changed it.
In this case, type() and __class__ do exactly the same thing. The only
way I know of (in Py3) to have them show different values is to make
__class__ a property, and if you do that, I have no idea what uses the
property and what uses type().

Maybe this needs to be actually documented somewhere. It keeps on
being a point of confusion.

ChrisA
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to