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

Stuart D. Gathman stuart at bmsi.com
Fri Jan 3 01:35:37 CET 2003


On Thu, 02 Jan 2003 15:04:24 -0500, 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)?
 
Downcasting in C++ is something you do to pointers, not to instances.
Here is how you "downcast" in Python:

class Base:
  def foo(self): print "base"

class Derived(Base):
  def bar(self): print "derived"

baseptr = Derived()	# C++: Base *baseptr = new Derived();

baseptr.bar()		# C++: ((Derived)baseptr)->bar();
# prints "derived"

Note that you do it exactly the same as in C++ - but without any type
attached to the reference variables (only instances have types in Python).

-- 
	      Stuart D. Gathman <stuart at bmsi.com>
Business Management Systems Inc.  Phone: 703 591-0911 Fax: 703 591-6154
"Confutatis maledictis, flamis acribus addictis" - background song for
a Microsoft sponsored "Where do you want to go from here?" commercial.




More information about the Python-list mailing list