Search code examples
pythonclassinheritancecom

How to define class in python and inherit a COM object properties?


I am trying to define a new class in python and inherit the properties of an existing COM object.

Here is my code so far:

import win32com.client
excel=win32com.client.Dispatch('Excel.Application')
excelapp.Visible=1 #opens excel window
class XL(excelapp):
    def __init__(self):
        excelapp.__init__(self)
XL.Visible=1 #does not work

Basically all I want to do is inherit the COM object into my own class so I can add some functions/operations that I can just call as XL.function_name() and also be able to use all the functions available using excelapp.function_name().

I realize I may be asking this in a confusing way because I do not know alot about this and know even less about COM objects, but appreciate any feedback or help anyone could provide!

Thanks!!


Solution

  • For those interested..from what I can tell, it's not possible to directly "inherit" the COM object properties but you can basically define a class as a workaround in the following way:

    import win32com.client
    
    class WORD(object):
    
        def __init__(self):
            self.word = win32com.client.Dispatch("Word.Application")
    
        def __getattr__(self, n):
            try:
                attr = getattr(self.word, n)
            except:
                attr = super(WORD, self).__getattr__(n)
            return attr
    
        def __setattr__(self, attr, n):
            try:
                setattr(self.word, attr, n)
            except:
                super(WORD, self).__setattr__(attr, n)    
    
    app = WORD()
    

    Then the app object should have all the functionality of the COM object made using the win32com.client.Dispatch command, and you will be able to add your own custom methods to the class.