为什么类“QuoteClientFactory”没有被理解为pycharm中的定义?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么类“QuoteClientFactory”没有被理解为pycharm中的定义?相关的知识,希望对你有一定的参考价值。

我正在学习网络编程与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()
答案

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

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()

以上是关于为什么类“QuoteClientFactory”没有被理解为pycharm中的定义?的主要内容,如果未能解决你的问题,请参考以下文章

Unity脚本类为啥要尽量避免继承MonoBehaviour类

Java 动态代理是基于什么原理(还没整理完)

同一个MFC工程中的两个普通类,为啥一个构造函数打点有反应,一个构造函数打点没反应?是因为设置问题吗

UML图六种箭头含义

抽象类

visio2013 双击UML类图 没属性框