Downcast (I know it sounds silly, but ...)

Jp Calderone exarkun at intarweb.us
Thu Jan 2 21:29:09 CET 2003


On Thu, Jan 02, 2003 at 08:04:24PM +0000, Rocco Rossi wrote:
> I was wondering if it is possible in Python to do something analogous to
> downcasting in a statically typed language like C++. I mean is it possible
> to take an instance of a base class and magically transform it into an
> instance of some derived class eventually fixing things (like the missing
> attribute data)?

  Since you can't cast in Python, the short answer is no.  A different
answer might take the form of...

class Foo:
    def foo(self):
        print 'I am foo'

class Bar:
    def bar(self):
        print 'I am bar'

f = Foo()
f.foo()
f.__class__ = Bar
f.bar()

  Notice that Bar isn't even a subclass of Foo.  I'll refrain from pointing
out that downcasting an "object" in C++ to a class lower in the inheritance
hierarchy than it actually is is an error and only works because C++ is
weakly typed (because this isn't comp.lang.c++ ;)

  hoping-you-don't-do-this'ly yours,

     Jp

-- 
In the days when Sussman was a novice Minsky once came to him as he sat
hacking at the PDP-6. "What are you doing?" asked Minsky. "I am training a
randomly wired neural net to play Tic-Tac-Toe." "Why is the net wired
randomly?" asked Minsky. "I do not want it to have any preconceptions of how
to play." Minsky shut his eyes. "Why do you close your eyes?" Sussman asked
his teacher. "So the room will be empty." At that moment, Sussman was
enlightened.
 --
 12:00am up 17 days, 9:46, 3 users, load average: 0.70, 0.74, 0.79
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20030102/84b70b7f/attachment.pgp>


More information about the Python-list mailing list