2014-04-20 139 views
1

如果我有兩個功能,(一個在另一個裏面);如何在另一個函數內調用函數?

def test1(): 
    def test2(): 
     print("test2") 

我怎麼叫test2

+0

你應該澄清你的問題:你的意思是如何把它從裏面'test1'打電話,或者從外面?正如這兩個答案所示,答案要麼是「顯而易見的方式」,要麼是「你不能」。 – BrenBarn

+1

如果你想在'test1' *之外使用'test2',你可以像其他任何對象一樣返回它 - 這就是裝飾器的工作原理。 – jonrsharpe

+0

我會用'return test2'返回嗎? @jonrsharpe –

回答

3

你可以把它也以此方式:

def test1(): 
    text = "Foo is pretty" 
    print "Inside test1()" 
    def test2(): 
     print "Inside test2()" 
     print "test2() -> ", text 
    return test2 

test1()() # first way, prints "Foo is pretty" 

test2 = test1() # second way 
test2() # prints "Foo is pretty" 

讓我們來看看:

>>> Inside test1() 
>>> Inside test2() 
>>> test2() -> Foo is pretty 

>>> Inside test1() 
>>> Inside test2() 
>>> test2() -> Foo is pretty 

如果你不想叫test2()

test1() # first way, prints "Inside test1()", but there's test2() as return value. 
>>> Inside test1() 
print test1() 
>>> <function test2 at 0x1202c80> 

讓我們更加努力:

def test1(): 
    print "Inside test1()" 
    def test2(): 
     print "Inside test2()" 
     def test3(): 
      print "Inside test3()" 
      return "Foo is pretty." 
     return test3 
    return test2 

print test1()()() # first way, prints the return string "Foo is pretty." 

test2 = test1() # second way 
test3 = test2() 
print test3() # prints "Foo is pretty." 

讓我們來看看:

>>> Inside test1() 
>>> Inside test2() 
>>> Inside test3() 
>>> Foo is pretty. 

>>> Inside test1() 
>>> Inside test2() 
>>> Inside test3() 
>>> Foo is pretty. 
3
def test1(): 
    def test2(): 
    print "Here!" 
    test2() #You need to call the function the usual way 

test1() #Prints "Here!" 

注意,test2功能不是test1外提供。例如,如果您稍後在代碼中嘗試致電test2(),則會發生錯誤。

+0

如果'test1'中有多個函數會怎麼樣? –

+1

@zachgates他們仍然只能在test1中調用。 –

+0

在test1中定義的任何函數只能在test1中使用。如果您想稍後使用該功能,則需要在test1之外定義它 – sredmond

0

您不能,因爲test2一旦test1()已返回就停止存在。要麼從外部函數返回它,要麼從那裏調用它。

+0

這是正確的,如果他的意思是「我怎樣從'test1'外面調用'test2'」,但是如果他問的是如何從'test1'內部調用它的話。 (這個問題不清楚。) – BrenBarn

相關問題