Could Python supplant Java?
James J. Besemer
jb at cascade-sys.com
Fri Aug 23 08:18:52 EDT 2002
Roy Smith wrote:
> To make Paul's point even stronger, it not just depends on the caller,
> but it may depend on run-time events. Imagine something like the
> following (with A and B classes as Paul described them):
>
> which version of bar() should get called is truly random and only known
> at run time.
By now you should have read my lengthy reply to Paul.
Fact of the matter, C++'s polymorphism even works in "dynamic" cases like you
cite here. Function and Object factories actually are common in C++.
The following is valid C++:
class A {
int x;
virtual int bar(){ return 1; }
};
class B {
int y;
virtual int bar(){ return 2; }
}
A* myFactoryFunction()
{
if( rand() ? 1 ){
return new A;
} else {
return new B;
}
}
void test()
{
A* ab = myFactoryFunction();
ab->bar() // calls A.bar() or B.bar() depending on instance
sub-type
ab->x; // always accesses A.x
ab->y; // !!compiler error -- A.y does not always exist
delete ab;
}
The only restriction over Python is that one of A or B would have to be
derrived from the other. More commonly you have multiple sub-types derrived
from a common super type. But this is usually the case if you're mixing them
together like this in the first place. Also, bar() has to be a function, not
a variable.
I find the third use of myFactoryFunction interesting in that it produces a
compile time error in C++ while in Python it will produce a runtime error
half the time.
--jb
P.S. there is a slight bug in my previous example. (Of course!) Either the
classes need to be declared instead as "structs" or else an explicit
"public:" access designation needs to be added to make the fields public.
--
James J. Besemer 503-280-0838 voice
http://cascade-sys.com 503-280-0375 fax
mailto:jb at cascade-sys.com
More information about the Python-list
mailing list