2017-10-18 109 views
0

我在兩個文件中有2個python類。yield在python中返回None?

  • 文件:LdapConnection,類:LdapClass(),方法:getMachines(個體)

    @defer.inlineCallbacks 
    def getMachines(self): 
        c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) 
        overrides = {self.basedn: (self.serverip, 389)} 
        client = yield c.connect(self.basedn, overrides=overrides) 
        yield client.bind(self.binddn, self.bindpw) 
        o = ldapsyntax.LDAPEntry(client, self.basedn) 
        results = yield o.search(filterText=self.query) 
        for entry in results: 
         for i in entry.get('name'): 
          self.machineList.append(i) 
    
        yield self.machineList 
        print self.machineList 
        return 
    

上述打印語句打印所有entires在machineList

  • 文件:扭曲的,類:緩存,方法:loadSettings(self)

    @defer.inlineCallbacks 
    def loadSettings(self): 
    
        returned = yield LdapClass().getMachines() 
        print returned 
    

在上面的類我的打印打印None。我在這裏做錯了什麼?

+0

我試圖格式化您的代碼,但它之前真的被打破。所以我不確定我是對的。請檢查。 – Sraw

+0

[Python中的yield表達式的結果是什麼?](https://stackoverflow.com/questions/10695456/what-is-the-result-of-a-yield-expression-in-python) – Aaron

+0

你可以減少你的例子到[最小,完整和可驗證的例子](https://stackoverflow.com/help/mcve)?很難獲得您看到的確切輸出。你對產量的使用確實很好奇。 'yield'和'return'的組合看起來是可疑的,因爲從函數返回值併產生列表而不是單個項目。我期望循環產量或'從'產量',但我意識到你正在使用py2,它不具有從'產量'。 –

回答

0

看起來你loadSettings()程序產生的getMachines()發電機,而不是從生成的結果。也許前者應該做「yield from」?

+1

鑑於括號無印痕,她使用python 2'在3.3版本中引入了「產量」。 –

+0

**升級的時間!** –

+0

我同意。 Py 2現在已經死了(最後) –

2

getMachines(),不要yield self.machineList

在由defer.inlineCallbacks裝飾的方法中,產量執行的效果是直到參數(一個defer.Deferred對象)回調一個值(如果它不是defer.Deferred,它將繼續)。 (它與Python 3中的新關鍵字await類似。)您在loadSettings()中正確使用了此項。

getMachines(),你沒有defer.Deferred;你有一個list,所以它繼續。要將該值返回給調用者,請在方法結束時調用returnValue(self.machineList)