2016-09-22 69 views
0

有沒有什麼辦法可以訪問其他函數中的函數返回?獲取其他函數中的函數返回?

可能下一個代碼更多地解釋我想要做什麼。

class perro: 
    def coqueta(self, num1, num2): 
     self.num1 = num1 
     self.num2 = num2 
     return self.num1 + self.num2 

    def otro_perro(self, coqueta): 
     print otro_perro 




mascota = perro() 
ejemplo = mascota.coqueta(5,5) 
mascota.otro_perro() 

print ejemplo 

我怎樣才能第一defcoqueta)返回在第二個函數(otro_perro)打印?

+0

您能否澄清您的問題?你想實現什麼?代碼中還有一些可能的錯誤:例如,方法'otro_perro'中的參考'otro_perro'(作爲回報)未被初始化,並且與方法調用'self.otro_perro'不同,這會導致無限遞歸。 –

+0

@ M.Wymann _我可以如何獲得拳頭高清的回報? - 這是他的問題。 –

回答

0

這是怎麼回事?

mascota = perro() 
ejemplo = mascota.coqueta(5,5) 
mascota.otro_perro(ejemplo) 

,或者

mascota = perro() 
mascota.otro_perro(mascota.coqueta(5,5)) 
+0

你好,謝謝你的回答,這只是一個例子,我會做一個大數學calc,我想在第二個函數中使用結果。 –

0

成全它的perro類的屬性。那真的是整點類,模塊化,組織和封裝數據,而不必使用global的到處都是:

class perro: 
    def coqueta(self, num1, num2): 
     self.num1 = num1 
     self.num2 = num2 
     self._otro_perro = self.num1 + self.num2 

    def otro_perro(self): 
     print self._otro_perro 




mascota = perro() 
mascota.coqueta(5,5) 
mascota.otro_perro() # will print the value of self._orto_perro 

orto_perro之前添加額外的下劃線,因爲你已經使用的名稱爲您的方法。作爲一個無關的方面說明,類名稱是一個在Python中大寫的gereral。所以perro會變成Perro

+0

但它不起作用,它顯示我一個錯誤:S –

2

要麼將​​方法coqueta()的返回值轉換爲otro_perro(),要麼將otro_perro()直接調用coqueta()。您的代碼表明,你希望做的第一,所以這樣寫:

class Perro: 
    def coqueta(self, num1, num2): 
     result = big_maths_calculation(num1, num2) 
     return result 

    def otro_perro(self, coqueta): 
     print coqueta 

mascota = Perro() 
ejemplo = mascota.coqueta(5, 5) 
mascota.otro_perro(ejemplo) 

或者,你可以調用coqueta()otro_perro()

def otro_perro(self, num1, num2): 
     print self.coqueta(num1, num2) 

但需要你傳遞值num1num2分成otro_perro()

也許num1num2可能被認爲是屬於Perro類的屬性?

class Perro: 
    def __init__(self, num1, num2): 
     self.num1 = num1 
     self.num2 = num2 

    def coqueta(self): 
     result = big_maths_calculation(self.num1, self.num2) 
     return result 

    def otro_perro(self, coqueta): 
     print self.coqueta() # N.B. method call 

或者另一種可能是緩存的「大計算」的結果:

class Perro: 
    def __init__(self, num1, num2): 
     self.num1 = num1 
     self.num2 = num2 
     self.result = None 

    def coqueta(self): 
     if self.result is None: 
      self.result = big_maths_calculation(self.num1, self.num2) 
     return self.result 

    def otro_perro(self, coqueta): 
     print self.coqueta() # N.B. method call 

現在只需執行一次昂貴的計算在這種情況下,當你創建類,你可以指定它們需要時將其結果存儲起來供以後使用,而無需重新計算。