2015-10-12 28 views
1

我有一個python類和幾個函數,第一次調用2nd。但是,第二個從來沒有被召喚過。另外調用_method2()之後的行永遠不會執行。類內部函數不叫

class call_methods(): 
    def _method1(self, context): 
      print "Now call method 2"; 
      this._method2(context); 
      print "Finish"; 
      return {} 

    def _method2(self, context={}): 
      print "method 2 called" 
      return {} 

輸出:

Now call method 2 

只有第1次印刷陳述出來。

該問題類似於Function Not getting called,但解決方案建議,似乎並不適用於此。

+2

'self' <-->'this'? '_method2'的'self'作爲第一個參數在哪裏? –

+0

該代碼應該給你一個錯誤。你能從錯誤信息中學到什麼? –

+0

'this._method2(context)'應該是'self.',因爲你的self是實例的名稱,而不是像Javascript那樣。另外,您不需要用分號結束行。 –

回答

1
this._method2(context); ===> self._method2(context) 

this不存在python.You必須使用self。也;不needed.Instead遵循正確的indentation.Modify你的第二個功能

def _method2(self, context={}): 
+1

'_method2'的簽名缺少'self'。代碼(就像現在這樣)會起作用,但這是另一件需要注意的事情。 –

+0

這是一個在不同語言之間雜耍的問題。所以,我最終使用'this'而不是'self'。謝謝你的提示。 –

0

它應該是:

class call_methods(): 


    def _method1(self,context): 

     print "Now call method 2"; 

     this._method2(context); 

     print "Finish"; 

     return {} 


    def _method2(self, context={}): 

     print "method 2 called" 


     return {} 
1

你有名字this其中未定義,所以Python會抱怨。你可以改變你的第二個method_method2()採取論證self其中,在Python,是一種約定標誌着你已經創建並想引用類的instance

class call_methods: 
    def _method1(self, context): 
     print "Now call Method 2" 
     self._method2(context) 
     print "finish" 
     return {} 

    def _method2(self, context={}): 
     print "Method 2 Called" 
     return {} 

如果要使用通過_method1調用_method2實例你已經創建,則必須再次提供呼叫的self參數_methdo2()引用實例,這樣做是含蓄通過調用self參數的函數_method1

你改變後的輸出將是:

In [27]: cls1 = call_methods() 

In [28]: cls1._method1("con") 
Now call Method 2 
Method 2 Called 
finish 
Out[28]: {} 

P.S:無需括號()聲明一個類時,它沒有什麼區別。您可能需要在Python 2中查看New Style Classes

+0

感謝您的解釋。問題是使用'this'而不是'self'。但是,python從來沒有拋出錯誤/異常/警告使用不存在的變量/對象。它只是停止執行。 –