[Python] How do I pass in arguments when initializing an event handler with...

Discussão em 'Python' iniciado por Stack, Março 14, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use win32com.client.WithEvents and I'd like to be able to pass values to the initialization method. However, the input for the event handler is the class, not an instance of the class:

    import win32com.client

    #For my application this is what defines "document"
    labchart = win32com.client.Dispatch("ADIChart.Application")
    document = labchart.ActiveDocument

    #This is the definition
    ev = win32com.client.WithEvents(document, LabChartEventHandler)

    #This is not valid, but is what I want to get to
    ev = win32com.client.WithEvents(document, LabChartEventHandler(param1,param2))


    It is possible to do this afterwards, but is there a way to pass in arguments to the constructor, other than using previously defined variables that are in scope?

    #Workaround, not sure what happens if time elapses between initialization and these calls
    ev.param1 = param1
    ev.param2 = param2

    #Current setup
    param1 = 1
    param2 = 2

    class LabChartEventHandler:

    def __init__(self):
    #Grabs already defined param1, not ideal (in my opinion)
    self.param1 = param1
    self.param2 = param2

    Continue reading...

Compartilhe esta Página