"casting" Python objects

Gary Herron gherron at islandtraining.com
Wed May 22 19:59:37 EDT 2002


On Wednesday 22 May 2002 04:28 pm, DJW wrote:
> I know there is no such thing in Python as C-style casting, but I don't
> understand what idiom is supposed to be used instead.

This might get you what you want.  You can change the class of an
object to a different class with a simple assignment (see below).
This will not change of the objects attributes of values (which is
probably what you want), but it will change method lookup to the new
class (which, I think, is exactly what you want).

Here's an example of creating an object of type C and then changing it
to an object of type D.

First create two (trivial classes):

>>> class C:
...   pass
...
>>> class D:
...   pass
...

Then create an object of one class and print it:
>>> c = C()
>>> print c
<__main__.C instance at 0x81530f4>
>>>

The re-class the object and print again.
>>> c.__class__ = D
>>> print c
<__main__.D instance at 0x81530f4>
>>>


Try defining some methods on those two classes, and see what happens
when you call them.


Gary Herron






More information about the Python-list mailing list