Could anyone explain __class__?
Michael P. Soulier
msoulier at storm.ca
Sat May 19 11:30:18 EDT 2001
On 19 May 2001 08:15:10 -0700, MikeK <mkent at atlantic.net> wrote:
> I'm having trouble understanding the function of the built-in class method
> __class__. The documentation is terse, to say the least.
>
> From code examples (UserList.py, forex.), it appears that self.__class__()
> returns a new instance of the class of the instance in which it is called.
> This would imply that the new instances' __init__ method would be called,
> which would mean that you must make sure that you give __class__() the
> correct arguments, just like you would if you instantiated the class in
> the normal method (e.g. myInstance = UserList(<args>)).
>
> Am I right, wrong, close, or what?
Seems to be a reference to the class object.
>>> class Parent:
... pass
...
>>> parent = Parent()
>>> dir(parent)
[]
>>> parent.__class__
<class __main__.Parent at 0x8056b9c>
>>> class Parent:
... pass
...
>>> parent = Parent()
>>> dir(parent)
[]
>>> parent.__class__
<class __main__.Parent at 0x804dafc>
So here, parent.__class__ is the same as Parent, so calling it as a
function would return a new instance of that class.
BTW, does anyone know why dir(parent) did not show __class__ as one of the
attributes? Does it not show inherited attributes?
Cheers,
Mike
--
Michael P. Soulier <msoulier at storm.ca>
"With sufficient thrust, pigs fly just fine. However, this is not necessarily a
good idea. It is hard to be sure where they are going to land, and it could be
dangerous sitting under them as they fly overhead." -- RFC 1925
More information about the Python-list
mailing list