2015-10-22 65 views
0

在python中,每個變量都定義爲全局範圍嗎?有人可以用下面的例子來解釋python的變量作用域嗎?這是Python 2.7版,但我不介意一個Python 3的解釋Var範圍Python

的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 

編輯看到這個帖子Python class scoping rules,但我仍然感到困惑。

+0

theres很多信息在你發佈的鏈接,所以也許澄清什麼仍然讓你感到困惑? –

+0

'$ test'沒有在'fun()'範圍聲明爲全局的,你不能訪問它,調用'fun($ test);' –

回答

0

您在Python中定義了一個全局變量test,全局變量可以在函數中訪問。要在PHP中達到相同的效果,您必須編寫以下代碼:

<?php 

$test = [1,2,3]; 

var_dump($test); 


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

fun(); 

可以達到相同的效果。你可以找到更多關於Python變量範圍here的信息。

+0

這樣做很有意義,並且感謝你的鏈接 – c3cris