变量作用域Python


Var scope Python

在python中每个变量都定义为全局作用域吗?有人能用下面的例子解释一下python的变量作用域吗?这是python 2.7的,但我不介意python 3的解释

Python

test = [1,2,3]
print test
def fun():
    print test
fun()
输出:

[1, 2, 3] 
[1, 2, 3] 
PHP

<?php
$test = [1,2,3];
var_dump($test);

function fun()
{
   var_dump($test); 
}
fun();
?>
输出:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
NULL
PHP Notice:  Undefined variable: test in /home/coderpad/solution.php on line 10

EDIT看到这个帖子Python类作用域规则,但我仍然感到困惑。

您在Python中定义了一个全局变量test,全局变量可以在函数中访问。要在PHP中达到同样的效果,您必须这样写:

<?php
$test = [1,2,3];
var_dump($test);

function fun()
{
   global $test; // <---- add this
   var_dump($test); 
}
fun();

来达到同样的效果。您可以在这里找到有关Python变量作用域的更多信息。