hniksic at xemacs.org
Tue Oct 26 11:21:07 CEST 2010
John Nagle <nagle at animats.com> writes:
> On 10/25/2010 7:38 AM, Tim Chase wrote:
>> While a dirty hack for which I'd tend to smack anybody who used it...you
>> *can* assign to instance.__class__
> That's an implementation detail of CPython. May not work in
> IronPython, Unladen Swallow, PyPy, or Shed Skin.
> (An implementation with a JIT has to trap stores into some
> internal variables and invalidate the generated code.
> This adds considerable complexity to the virtual machine.
> Java JVMs, for example, don't have to support that.)
A Python implementation probably looks up attributes via type late at
runtime anyway, so modifying __class__ boils down to changing a
reference inside the (moral equivalent of the) PyObject structure.
For example, assigning to __class__ appears to work just fine in Jython
Jython 2.5.2rc2 (Release_2_5_2rc2:7167, Oct 24 2010, 22:48:30)
[OpenJDK 64-Bit Server VM (Sun Microsystems Inc.)] on java1.6.0_18
Type "help", "copyright", "credits" or "license" for more information.
>>> class X(object):
>>> class Y(X): pass
>>> x = X()
>>> x.__class__ = Y
<__main__.Y object at 0x3>
More information about the Python-list