python - 如果 python 运行文件 "line after line"它如何在定义之前使用函数?

标签 python

我现在正在学习Python,在学习Java之后,现在我知道java首先编译整个文件然后运行它,在Python中,根据我的理解,它在“逐行”编译它的同时运行程序。

所以我不明白的是如何在定义函数之前调用它。 我习惯于在 Java 中将所有“帮助方法”写在需要它们的方法之后,我认为这样更容易阅读。 所以我尝试在 python 中做同样的事情,并且成功了。 为什么?

最佳答案

这里的一个重要标志是,创建函数的顺序并不重要,函数调用何时完成才重要。 p>

以下面的代码为例:

def add_one(new):
    return my_add(new, 1)

def my_add(x, y):
    return x + y

my_var = 2
print("The value of my_var is: {}".format(my_var))
my_var = add_one(my_var)
print("The value of my_var is: {}".format(my_var))

结果

The value of my_var is: 2

The value of my_var is: 3

发生这种情况是因为在调用 add_one 函数时,两个函数都已经存在。但如果在定义 my_add 之前尝试调用 add_one...

def add_one(new):
    return my_add(new, 1)

my_var = 2
print("The value of my_var is: {}".format(my_var))
my_var = add_one(my_var)
print("The value of my_var is: {}".format(my_var))

def my_add(x, y):
    return x + y

我们得到:

The value of my_var is: 2
Traceback (most recent call last):
  File "c:\Users\wundermahn\Desktop\Stack.py", line 6, in <module>
    my_var = add_one(my_var)
  File "c:\Users\J39304\Desktop\Stack.py", line 2, in add_one
    return my_add(new, 1)
NameError: name 'my_add' is not defined

参见Does the order of functions in a Python script matter?了解更多

关于python - 如果 python 运行文件 "line after line"它如何在定义之前使用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59382335/

相关文章:

Python看门狗: Why is my subprocess called continuously?

python - Tastypie:queryset = Model.objects.all()

python - 实现一种算法以确定字符串是否具有所有唯一字符

python - 在 Python 中测试数学表达式的等价性

Python:urlretrieve PDF 下载

Python绘图桑基并确定节点的顺序

javascript - 无法在 python/flask 中使用 jQuery 解析通过 AJAX 发出的 JSON POST 请求

python - Django 和 Bootstrap : Knowing Which Tab is Active

python - 用字符串替换列中的某些值

python - MySQL 中出现错误 1146 的问题