我认识到这可能是一个非常类型为101的问题,但是总体上我仍然难以理解函数式编程,并且有一个我无法理解的特定代码段:
完整代码,但忽略了大多数函数定义:
import blpapi
import sys
SESSION_STARTED = blpapi.Name("SessionStarted")
SESSION_STARTUP_FAILURE = blpapi.Name("SessionStartupFailure")
SERVICE_OPENED = blpapi.Name("ServiceOpened")
SERVICE_OPEN_FAILURE = blpapi.Name("ServiceOpenFailure")
ERROR_INFO = blpapi.Name("ErrorInfo")
GET_FILLS_RESPONSE = blpapi.Name("GetFillsResponse")
d_service="//blp/emsx.history"
d_host="localhost"
d_port=8194
bEnd=False
class SessionEventHandler():
def processEvent(self, event, session):
try:
if event.eventType() == blpapi.Event.SESSION_STATUS:
self.processSessionStatusEvent(event,session)
elif event.eventType() == blpapi.Event.SERVICE_STATUS:
self.processServiceStatusEvent(event,session)
elif event.eventType() == blpapi.Event.RESPONSE:
self.processResponseEvent(event)
else:
self.processMiscEvents(event)
except:
print ("Exception: %s" % sys.exc_info()[0])
return False
def processSessionStatusEvent(self,event,session):
print ("Processing SESSION_STATUS event")
for msg in event:
pass
def processServiceStatusEvent(self,event,session):
print ("Processing SERVICE_STATUS event")
for msg in event:
pass
def processResponseEvent(self, event):
print ("Processing RESPONSE event")
for msg in event:
global bEnd
bEnd = True
def processMiscEvents(self, event):
print ("Processing " + event.eventType() + " event")
for msg in event:
print ("MESSAGE: %s" % (msg.tostring()))
def main():
sessionOptions = blpapi.SessionOptions()
sessionOptions.setServerHost(d_host)
sessionOptions.setServerPort(d_port)
print ("Connecting to %s:%d" % (d_host,d_port))
eventHandler = SessionEventHandler()
session = blpapi.Session(sessionOptions, eventHandler.processEvent)
if not session.startAsync():
print ("Failed to start session.")
return
global bEnd
while bEnd==False:
pass
session.stop()
我可以遵循以下代码:
session = blpapi.Session(sessionOptions, eventHandler.processEvent)
在这里,我看到我正在从blpapi库中调用“会话”,并将其传递给一些选项以及eventHandler.processEvent。这是我迷路的地方。我查看了该特定功能,然后看到:
def processEvent(self, event, session):
try:
if event.eventType() == blpapi.Event.SESSION_STATUS:
self.processSessionStatusEvent(event,session)
elif event.eventType() == blpapi.Event.SERVICE_STATUS:
self.processServiceStatusEvent(event,session)
elif event.eventType() == blpapi.Event.RESPONSE:
self.processResponseEvent(event)
else:
self.processMiscEvents(event)
except:
print ("Exception: %s" % sys.exc_info()[0])
return False
我看到该函数正在尝试识别传入的事件类型,并将根据该事件类型在类中执行不同的函数。麻烦的是,我不知道该事件在哪里指定! “事件”从何而来?我将其视为该特定函数中的参数,但未将事件参数传递给:
session = blpapi.Session(sessionOptions, eventHandler.processEvent)
那么它如何知道此时该怎么办?这个“事件”对象如何神奇地出现?
感谢您回答我的愚蠢问题
答案 0 :(得分:1)
session = blpapi.Session(sessionOptions, eventHandler.processEvent)
请注意,此处的processEvent
之后没有括号()
。这意味着您要将函数本身作为参数传递给Session
类。此类稍后将使用适当的参数调用processEvent
。
旁注:
我在理解函数式编程方面仍然遇到困难
“函数式编程”有一个非常具体的定义,而这个例子不是。如果您有兴趣,可以在Google上进行“函数式编程”或阅读Wikipedia文章以了解更多信息。但是,这在您的学习过程中并不十分重要。