如何将VB委托转换为python事件处理程序?

2024-10-02 18:20:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须使用python.net将以下订阅委托(事件)的VB代码重写为python

Imports MtApi

Public Class Form1
    Private apiClient As MtApiClient

    Public Sub New()
        InitializeComponent()
        apiClient = New MtApiClient
        AddHandler apiClient.QuoteUpdated, AddressOf QuoteUpdatedHandler
    End Sub

    Sub QuoteUpdatedHandler(sender As Object, symbol As String, bid As Double, ask As Double)
        Dim quoteSrt As String
        quoteSrt = symbol + ": Bid = " + bid.ToString() + "; Ask = " + ask.ToString()
        ListBoxQuotesUpdate.Invoke(Sub()
                                       ListBoxQuotesUpdate.Items.Add(quoteSrt)
                                   End Sub)
        Console.WriteLine(quoteSrt)
    End Sub

    ' These can be ignored for this discussion
    Private Sub btnConnect_Click(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
        apiClient.BeginConnect(8222)
    End Sub

    Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
        apiClient.BeginDisconnect()
    End Sub
End Class

此VB代码是mtapi.NET网桥的VB应用程序的一部分。

Q:将此VB委托转换为python事件处理程序的正确方法是什么?


我已经尝试了以下多种方法:

...
import MtApi as mt
...
# apiClient_QuoteUpdated(object sender, string symbol, double bid, double ask)
def printTick(symbol, ask, bid):
    print('Tick: Symbol: {}  Ask: {:.5f}  Bid: {:.5f}'.format(symbol, ask, bid))


class OnTick:
    def __init__(self):
        self.listeners = []

    def __iadd__(self, listener):
        # Shortcut for using += to add a listener
        self.listeners.append(listener)
        return self

    def notify(self, *args, **kwargs):
        for listener in self.listeners:
            listener(*args, **kwargs)

mtc = mt.MtApiClient()
res = mtc.BeginConnect('127.0.0.1', 8222);

# This Works!
newTick = OnTick()
newTick += printTick
newTick.notify(SYM, 1.12400, 1.12300)

# This does NOT work!
newTick.notify(mtc.QuoteUpdate())
# TypeError: 'EventBinding' object is not callable

我一直在这里寻找答案:


Tags: selfdefassymbolsystemsenderaskend
1条回答
网友
1楼 · 发布于 2024-10-02 18:20:29

与类似问题中的this answer密切相关的是,问题在于委托代码过于复杂。我们不需要OnTick类,也不需要意识到QuoteUpdatedHandler()需要4个参数,所以我们用它来替换printTick(...)

(当然,如果您确实希望使某些内容变得更复杂或更优雅,那么您确实希望在类中创建它。)

然后,VB委托的等效Python代码变为:

...
def QuoteUpdatedHandler(source, sym, bid, ask) :
    qstr = '{}: {:.5f} {:.5f}'.format(sym,bid,ask)
    print(qstr)

...
mtc = mt.MtApiClient()

print('Connecting...')
res = mtc.BeginConnect('127.0.0.1', 8222);

# VB: AddHandler mtc.QuoteUpdated, AddressOf QuoteUpdatedHandler
# Because we want the "AddressOf" of the function, we don't use the invoking "()"
mtc.QuoteUpdated += QuoteUpdatedHandler

print('ok')

# Now run in a loop and wait for the events:
while 1:
    pass
    try: 
        time.sleep(0.1)
    except KeyboardInterrupt:
        print('\n  Break!')
        break

if (mtc.IsConnected()) :
    mtc.PlaySound("tick")
    mtc.BeginDisconnect()
print('\n  Done!')

sys.exit(2)

相关问题 更多 >