【问题标题】:How come the class "QuoteClientFactory" is not being understood as Defined in pycharm?为什么“QuoteClientFactory”类不被理解为在pycharm中定义?
【发布时间】:2017-12-31 17:24:33
【问题描述】:

我正在使用 o'REilys Twisted 网络编程必备指南学习网络编程。 (使用 pycharm IDE)

我有两个问题,pycharm 中没有识别函数 maybeStopReactor() 并且没有将 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()

【问题讨论】:

  • 你不能在定义结束之前引用一个类,因为它还没有定义。请注意,在类定义期间不会执行方法体,因此可以在其自己的方法中使用该类。也许你想取消从quotes = ...开始的所有内容

标签: python networking pycharm twisted


【解决方案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()

【讨论】:

  • 在扭曲的书中,示例输出是“收到的报价:早起的鸟儿有虫吃”,但我得到的只是收到的报价:您对如何解决这个问题有什么建议吗?我不确定要寻找什么?
  • 您使用的是哪个版本的 Python?
  • 我正在使用 Python 3.6.2,并且我正在将 pycharm 用于 IDE。我应该尝试另一个 IDE 吗?
  • 导致问题的行是dataReceived 类的dataReceived 方法中的print "Received quote:", dataQuoteProtocol。鉴于您使用的是 Python 3,您必须重构该行。试试print(f"Received quote: {data}")
  • 谢谢您,非常感谢您的帮助!这似乎解决了这个问题!如果没有你的帮助,我怎么会弄明白呢?我可以用谷歌搜索什么或文档?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2021-05-01
相关资源
最近更新 更多