[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

OT: This Swift thing

On Fri, Jun 6, 2014 at 9:02 AM, Sturla Molden <sturla.molden at gmail.com> wrote:
> You cannot spoof the type of an object in Python.

Not without fiddling around. Python 3.4 on win32:

>>> class Foo:
    def spam(self):

>>> class Bar:
    def spam(self):
        print(self,"eats spam")

>>> x = Foo()
>>> x.spam()
<__main__.Foo object at 0x0169AB10> spams
>>> x.__class__ = Bar
>>> x.spam()
<__main__.Bar object at 0x0169AB10> eats spam

The thing has the same id (as shown in its repr), but has changed
class. However, you can't turn it into an int:

>>> x.__class__ = int
Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    x.__class__ = int
TypeError: __class__ assignment: only for heap types

So there are limits. (Obviously with ctypes you can do anything, but
at that point, you're not working with Python any more, you're
fiddling with CPython's RAM. That's quite different.)