怎么来上课" QuoteClientFactory"是不是被理解为pycharm中的定义?

时间:2017-12-31 17:24:34

标签: python networking pycharm twisted

我正在学习网络编程与o' REilys Twisted网络编程必不可少的指南。 (使用pycharm IDE)

我有两个问题,函数maybeStopReactor()在pycharm中未被识别,而QuoteClientFactory不被视为已定义的类。

我如何为此寻找解决方案?

class QuoteClientFactory(protocol.ClientFactory):
    def __init__(self, quote):
        self.quote = quote

    def buildProtocol(self, addr):
        return QuoteProtocol(self)

    def clientConnectionFailed(self, connector, reason):
        print("connecton failed:"), reason.getErrorMessage()
        **maybeStopReactor()**

    def clientConnectionLost(self, connector, reason):
        print("connection lost"), reason.getErrorMessage()
        maybeStopReactor()

    def maybeStopReactor(self):
        global quote_counter
        quote_counter -=1
        if not quote_counter:
            reactor.stop()

    quotes = [
        "you snooze you lose",
        "The early bird gets the worm",
        "carpe diem"
    ]

    quote_counter = len(quotes)

    for quote in quotes:
        **reactor.connectTCP('localhost', 6942, QuoteClientFactory(quote))**
    reactor.run()

1 个答案:

答案 0 :(得分:1)

你的缩进是错误的。这有点难以看清,因为代码跨越了分页符。你想要的是:

class QuoteClientFactory(protocol.ClientFactory):
    def __init__(self, quote):
        self.quote = quote

    def buildProtocol(self, addr):
        return QuoteProtocol(self)

    def clientConnectionFailed(self, connector, reason):
        print("connecton failed:"), reason.getErrorMessage()
        maybeStopReactor()

    def clientConnectionLost(self, connector, reason):
        print("connection lost"), reason.getErrorMessage()
        maybeStopReactor()

def maybeStopReactor():
    global quote_counter
    quote_counter -=1
    if not quote_counter:
        reactor.stop()

quotes = [
    "you snooze you lose",
    "The early bird gets the worm",
    "carpe diem"
]

quote_counter = len(quotes)

for quote in quotes:
    reactor.connectTCP('localhost', 6942, QuoteClientFactory(quote))
reactor.run()