在python中声明它们的主体之前是否可以使用函数?

dev*_*ium 13 python

在实际声明它们的主体之前,有没有办法在文件中使用函数?

以下代码似乎不起作用:

abc = myFunction

def myFunction():
    print "123"
Run Code Online (Sandbox Code Playgroud)

谢谢

Joh*_*kin 20

您无法myFunction在分配变量之前使用该变量.您的示例代码类似于:

def myFunction():
    print abc
    abc = 123
Run Code Online (Sandbox Code Playgroud)

要做你想做的事,要么重新安排订单:

def myFunction():
    print "123"

abc = myFunction
Run Code Online (Sandbox Code Playgroud)

或者声明abc只是一个代理:

# Style 1
abc = lambda: myFunction()

# Style 2
def abc():
    return myFunction()

def myFunction():
    print "123"
Run Code Online (Sandbox Code Playgroud)

如果您的函数采用参数,请使用*args和**kwargs:

# Style 1
abc = lambda *args, **kwargs: myFunction(*args, **kwargs)

# Style 2
def abc(*args, **kwargs):
    return myFunction(*args, **kwargs)

def myFunction(x):
    print x
Run Code Online (Sandbox Code Playgroud)


Gre*_*ill 13

您可以声明使用前向声明的函数,但Python 从上到下执行源代码.所以,这将编译并运行:

def foo():
    print "in foo"
    bar()

def bar():
    print "in bar"
    foo()

foo()
Run Code Online (Sandbox Code Playgroud)

(当然,它会在运行时导致堆栈溢出).在您的示例中,Python正在执行该行

abc = myFunction
Run Code Online (Sandbox Code Playgroud)

之前myFunction被定义为任何东西.您可以通过交互式地将源代码输入到解释器中来考虑这一点.当您输入作业时,您甚至不会输入定义myFunction,因此Python无法引用它.

另一种看待这种情况的方法可能如下:

>>> myFunction = "hello"
>>> abc = myFunction
>>> def myFunction():
...     print "there"
... 
>>> abc
'hello'
>>> myFunction
<function myFunction at 0x63270>
>>> myFunction()
there
Run Code Online (Sandbox Code Playgroud)

如您所见,myFunction函数的定义只是更改了符号myFunction与函数对象的绑定.