簡體   English   中英

如何調用另一個函數中定義的函數?

[英]How can I call a function defined in another function?

今天發現找不到在另一個函數內部調用一個函數的方法。 除非我在主函數中明確返回它或使用閉包結構。 但我想知道是否有另一種方式來稱呼它。 或者不是這么連貫,python允許我在函數內部定義函數,但不允許我以后以簡單的方式使用它們!

我的代碼是這樣的,我想在定義它們之后調用b(),c(),d()。

def a():
    def b():
        print 'b'
    def c():
        print 'c'
    def d():
        print 'd'
    print 'a'

>>> a()
a
>>> a.b
AttributeError: 'function' object has no attribute 'b'
>>> a.b()
AttributeError: 'function' object has no attribute 'b'

您不能從a的范圍之外調用這些函數。 他們被限制的范圍a

您可以像考慮函數中的其他本地名稱一樣考慮這些函數。 例如:

def foo():
    bar = 42

正如您不能在定義范圍之外引用本地函數一樣,您也不能在foo()范圍之外引用bar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM