gpt4 book ai didi

python - 使用前是否必须在 Python 中定义变量?

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:33 25 4
gpt4 key购买 nike

Python 是否很像 PHP,因为我可以调用一个变量,如果它不存在,它就会被创建?还是我需要申报?

最佳答案

在 PHP 中,如果您调用一个变量但它不存在,您将得到 Notice: Undefined variable。这不会创建它 - 再次执行相同的操作仍会返回警告。

php > echo $some_uninitialized_var;
PHP Notice: Undefined variable: some_uninitialized_var in php shell code on line 1
php > echo $some_uninitialized_var;
PHP Notice: Undefined variable: some_uninitialized_var in php shell code on line 1

在 Python 中,如果您调用一个变量但它没有被初始化,您将得到一个 NameError。同样的事情 - 它不会被创建 - 你会得到 NameError 直到你真正初始化它。

>>> print(some_uninitialized_var)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_uninitialized_var' is not defined

>>> print(some_uninitialized_var)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_uninitialized_var' is not defined

没有声明的初始化:

虽然在 PHP 和 Python 中,与 C 不同,您不需要在首次使用变量之前声明变量,这也许就是您的意思。您可以只分配它们,它们将在第一次分配时创建。

// PHP
$a_new_var = 12345;
// All is well...

# Python
a_new_var = 12345
# All is well...

// C
a_new_var = 12345;
// Crash! Horror! Compiler complains!
int a_new_var;
a_new_var = 12345;
// ok...

关于python - 使用前是否必须在 Python 中定义变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10134127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com