2013-12-22 53 views
0

這項工作?你可以調用一個以前沒有聲明過的函數嗎?

class Example: 
    def fun2(self): 
     fun1() 

    def fun1() 
     print "fun1 has been called" 

注意首位,而其上面fun1聲明-is調用fun1fun2。我很感興趣的是在類內部按順序調用函數時會發生什麼。

是否有任何情況下函數不會意識到另一個函數,即使函數的調用會被正確解決?

+0

@thefourtheye你錯過了這個問題的關鍵。班上應該有一個'fun1'。另外,我並不認爲這是一個「功能性」問題,因爲類命名空間與問題相關。 – seebiscuit

+0

更新了它。請立即檢查 – thefourtheye

+0

您的實際問題是什麼?你有沒有試過......運行你所問的代碼?我們不是你的翻譯。 – kqr

回答

2

起初代碼中函數調用fun2不起作用。它會拋出錯誤信息:NameError: global name fun1' is not defined是否因爲函數必須在被調用之前進行聲明?

No.It原來,異常被拋出,因爲fun1fun2範圍。瞭解名稱空間如何工作將照亮異常並回答發佈的問題。

任何函數的名稱空間首先是它自己的函數名稱空間,然後是全局名稱空間。它默認不包含'class'命名空間。但是,它確實(也應該)有權訪問類名稱空間。爲了讓函數知道它正在調用同一個類中的函數,必須在調用函數之前使用關鍵字self

那麼,這工作:

class Example: 
    def fun2(self): 
     self.fun1() # Notice the `self` keyword tells the interprter that 
        # we're looking for a function, `fun1`, that is relative to 
        # the same object (once a variable is declared as an Example 
        # object) where `fun2` lives. 

    def fun1(self): 
     print "fun1 has been called" 

# fun1 has been called 

現在fun1是參考能夠通過fun2,因爲fun2現在看看類的命名空間。我測試了,這是真的通過運行:

class Example: 
    def fun2(self): 
     fun1() 

    def fun1(self): 
     print "fun1 was called" 

def fun1(): 
    print "fun1 outside the class was called" 

沒有self關鍵字的輸出是:

fun1 outside the class was called 

所以,在這裏回答這個問題,當Python解釋腳本它預先編譯所有相關的命名空間。因此,所有功能都知道所有適當解決的其他功能,從而使原始聲明順序無關緊要。

+0

你答案的一部分讓我覺得'fun1'是爲了成爲問題代碼中類的一部分。是這樣嗎? – delnan

+0

@delnan是的。這是正確的。它已被重新編輯。 – seebiscuit

相關問題