Class type coercion

Gordon McMillan gmcm at hypernet.com
Wed Apr 5 10:41:21 EDT 2000


Robert Cragie

> (Apologies if this has been covered before, I'm a bit of a Python newbie)
> 
> I posted a question to wxWindows list, and got an answer from Robin Dunn,
> but it raised a more general question...
> 
> In C++, it is easy to use a pointer to a object declared as a super class of
> that object's class, and then coerce it to be the same class type as the
> object, e.g.
> 
> // Declare instance of class 'MyClass', which is derived from class
> 'MySuperClass'
> MyClass MyClassObj;
> 
> // Declare pointer to class 'MySuperClass'
> MySuperClass* pMySuperClass;
> 
> pMySuperClass = &MyClassObj; // OK, class 'MyClass' is derived from class
> 'MySuperClass'
> 
> // Coerce pointer to get to method which is only in class 'MyClass'
> ((MyClass*)pMySuperClass)->MyMethodOnlyInMyClass();
> 
> Can you do the equivalent in Python? I feel there must be some
> straightforward way to do this, I just haven't figured it out yet. Or is
> there...? As there is no type declaration in Python maybe this just isn't
> possible.

Python is completely dynamically bound, so the question 
doesn't arise.
a.MyMethodOnlyInMyClass() 
will either succeed or fail.

To find out if it will work, read up on isinstance().
 
> There is a real-world need for this e.g. parent Window object contains
> various child control objects. All the control classes are subclassed from
> the Window class. All control objects have an ID. There often exists a
> Window method to get a child window by ID. However, it can only return a
> type of Window class. Therefore, to get to the actual control, this return
> type needs to be subclassed.



- Gordon




More information about the Python-list mailing list