[python-win32] "Casting" COM objects
Mark Hammond
mhammond@skippinet.com.au
Tue, 8 Apr 2003 09:14:31 +1000
[Paul]
> Consider the following case:
>
> class A:
> def foo(self): pass
>
> class B(A):
> def bar(self): pass
>
> class C(A):
> def car(self): pass
>
> Now pretend Python had static typing:
>
> class Z:
> def __init__(self, thing):
> self.thing = thing
>
> def get_A() returns A:
> return self.thing
>
> Now in statically typed languages like C or IDL, it is perfectly legal
> for C to return a "B" because a B isa A. Then, client code casts from an
> A reference to a B reference to get access to the bar() function.
I think you are looking for the (fairly new) win32com.client.CastTo()
method - this takes an object and a class name. I came across this in the
Outlook object model:
Outlook has a "CommandBarItem" object, and subclasses for different types of
items (CommandBarPopup, CommandBarButton, etc).
There is an "AddControl()" method that takes the type of the object as a
param, but it is prototypes as returning the base "CommandBarItem".
I call:
ob = whatever.AddControl(..., type_popup,...) # ob is CommandBarItem
ob = CastTo(ob, "CommandBarPopup") # ob is CommandBarPopup
And magic happens :) 'ob' is different, but as per a previous coincidental
post, they will compare equal.
I *think* that is what you were asking :)
Mark.