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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1909325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:19:23  来源:igfitidea点击:

Is it possible to use functions before declaring their body in python?

python

提问by devoured elysium

Is there any way to make possible to use functions in your file before you actually declare their body?

在实际声明函数体之前,有什么方法可以使用文件中的函数?

The following code doesn't seem to work:

以下代码似乎不起作用:

abc = myFunction

def myFunction():
    print "123"

Thanks

谢谢

回答by John Millikin

You can't use the myFunctionvariable before it's assigned. Your example code is similar to:

您不能myFunction在分配之前使用该变量。您的示例代码类似于:

def myFunction():
    print abc
    abc = 123

To do what you want, either re-arrange the order:

要执行您想要的操作,请重新排列顺序:

def myFunction():
    print "123"

abc = myFunction

Or declare abcas just a proxy:

或者声明abc为一个代理:

# Style 1
abc = lambda: myFunction()

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

def myFunction():
    print "123"

If your function takes parameters, use *argsand **kwargs:

如果您的函数采用参数,请使用*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

回答by Greg Hewgill

You can declarefunctions that use forward declarations, but Python executesthe code in your source from top to bottom. So, this would compile and run:

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

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

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

foo()

(except it would cause a stack overflow at runtime, of course). In your example, Python is executingthe line

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

abc = myFunction

before myFunctionis defined as anything. You could think of this in terms of typing your source code interactively into the interpreter. When you type in your assignment, you wouldn't have even typed inthe definition of myFunctionyet, so Python wouldn't be able to refer to it.

beforemyFunction被定义为任何东西。您可以将源代码交互式地输入到解释器中。当您输入作业时,您甚至不会输入myFunction尚未定义的内容,因此 Python 将无法引用它。

Another way to look at this might be the following:

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

>>> myFunction = "hello"
>>> abc = myFunction
>>> def myFunction():
...     print "there"
... 
>>> abc
'hello'
>>> myFunction
<function myFunction at 0x63270>
>>> myFunction()
there

As you can see, the definition of the myFunctionfunction just changes the binding of the symbol myFunctionto a function object.

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

回答by jldupont

short answer is no.

简短的回答是否定的。

In Python, statements are evaluated along as they are parsed - myFunctionwasn't parsed so Python doesn't know about it.

在 Python 中,语句在被解析时被评估 -myFunction没有被解析,所以 Python 不知道它。

回答by jbochi

You can declare an empty function, use it to set attributes or anything like this, and then modify its code later.

你可以声明一个空函数,用它来设置属性或类似的东西,然后再修改它的代码。

def myFunction():
    pass

myFunction.foo = 'bar'

def makeFunction(obj):
    def myFunction():
        print "123"

    f = myFunction
    for attr in dir(obj):
        if attr not in dir(f):
            setattr(f, attr, getattr(obj, attr))

    return f


myFunction = makeFunction(myFunction)
myFunction()
print myFunction.foo

回答by Jim Dennis

Python will raise a NameError as it encounters any reference to any name (token that's a valid variable/class/function/object name) for which there was no previous binding.

Python 将在遇到对任何先前没有绑定的任何名称(令牌是有效的变量/类/函数/对象名称)的任何引用时引发 NameError。

The Python interpreter executes the source code of a file as it reads it. Thus def foo():is actually statement which defines foo()as the code is being loaded.

Python 解释器在读取文件时执行文件的源代码。因此def foo():实际上是定义foo()为正在加载代码的语句。

It's easy to think that forward references are supported. Consider this:

很容易认为支持前向引用。考虑一下:

def foo():
    return abc

abc="FooBar, Dude"

print foo()

... and you'll see that it can be run without issues. It's best to think of the definition of foo()as being quoted. The contents aren't evaluated until the function is invoked. So the NameError isn't raised (so long as some value has been bound to the name "abc" before the call to the function.

...你会看到它可以毫无问题地运行。最好将 的定义foo()视为被引用。在调用函数之前不会评估内容。因此不会引发 NameError (只要在调用函数之前将某些值绑定到名称“abc”。

Notice that some of these semantics are sufficiently different than those from languages like Java, C/C++, and Perl that Pythonistas often prefer to use slightly different terminology. Variables and such are called "names" and the process of associating those with values (or, more generally, objects) is referred to as "binding." So instead of "assigning values to variables" you are "binding objects to names."

请注意,其中一些语义与 Java、C/C++ 和 Perl 等语言的语义有很大不同,Pythonistas 通常更喜欢使用略有不同的术语。变量等称为“名称”,将它们与值(或更一般地说,对象)相关联的过程称为“绑定”。因此,不是“为变量赋值”,而是“将对象绑定到名称”。

Informally names, especially for simple numeric or string objects, are called "variables" and statements such as x='foo'are referred to as assignments. The semantics are usually similar enough that we won't care.

非正式的名称,尤其是简单的数字或字符串对象,被称为“变量”,而诸如x='foo'赋值的语句。语义通常足够相似,我们不会在意。