dynamic casting in python

Oliver Korpilla korpo at 01019freenet.de
Fri Apr 20 22:49:14 EDT 2001


Christian Reyes wrote:

> How do I do it?
> Is it possible?

Since Python does only concern about whether an object can receive the
right "messages" (has the right methods), not about type information as
more stongly typed languages, there is no type cast feature at all.
Upcasts are only needed to satisfy certain interface properties (like in
Java, where subclasses can fit interface types or super-types),
downcasts are only needed if an upcast took place (like in a Java
container, where you always upcast to Object, since there are no
templates, only dynamic binding to a single-rooted hierarchy).
Casting between different types not directly related has only some sense
among primitve types as numbers and strings, which Python supports.
Object types either needn't be casted , if they share interface data
(otherwise you would need to replace the methods on the data, etc.!).
Different "types" should exchange data through messages.
Create a new type operating on data handed over to it.
And if you really need changing type (or better appearing to have
changed type) you should rely on the State Pattern [Gang of Four, Design
Patterns], which allows objects to change behaviour if their state
changes (similar to type change).
All other is foolishness, I'd say, since it is not needed in a well
designed program. Please don't take this as an insult!

Hope I could help,
Ciao, Korpo




More information about the Python-list mailing list