OO in Python? ^^

Matthias Kaeppler void at void.com
Sun Dec 11 09:55:11 CET 2005


Heiko Wundram wrote:
> Brian Beck wrote:
> 
>>>class D1(Base):
>>>   def foo(self):
>>>      print "D1"
>>>
>>>class D2(Base):
>>>   def foo(self):
>>>      print "D2"
>>>obj = Base() # I want a base class reference which is polymorphic
>>>if (<need D1>):
>>>   obj =  D1()
>>>else:
>>>   obj = D2()
>>
>>I have no idea what you're trying to do here and how it relates to
>>polymorphism.
>>
> 
> 
> He's translating C++ code directly to Python. obj = Base() creates a
> variable of type Base(), to which you can assign different object types (D
> (), D2()) which implement the Base interface (are derived from Base).
> Err... At least I think it's what this code is supposed to mean...
> 
> In C++ you'd do:
> 
> Base *baseob;
> 
> if( <i want d1> ) {
>     baseob = (Base*)new D1();
> } else {
>     baseob = (Base*)new D2();
> }
> 
> baseob->foo();
> 
> (should, if foo is declared virtual in Base, produce "d1" for D1, and "d2"
> for D2)
> 
> At least IIRC, it's been quite some time since I programmed C++... ;-)
> *shudder*

Yes, that's what I tried to express (the cast to Base* is redundant here 
by the way, since D1/D2 are also of type Base; you can always hold a 
base class pointer to derived types without type conversion).

I have also read the other answers to my question, and I am really sorry 
if I have sounded ignorant in my post, but it's harder than I thought to 
move to a language where all these techniques one had learned in years 
of hard work suddenly become redundant :)
I'm so used to statically typed languages that the shift is very 
confusing. Looks as if it isn't as easy to learn Python afterall, for 
the mere reason of unlearning rules which don't apply in the world of 
Python anymore (which seem to be quite a lot!).

Regards,
Matthias




More information about the Python-list mailing list