Python全域性變數與區域性變數詳解
#Python中的變數:全域性變數和區域性變數 #在很多語言中,在宣告全域性變數的時候,都喜歡把全域性變數的名稱定義為大寫 #定義學生人數為100 STUDENT_NUMBER = 100 #學校名稱 SCHOOL_NAME = 'Guangzhou University' """\ 獲取全域性變數:學生人數STUDENT_NUMBER的值 """ def getStudentNumber(): return STUDENT_NUMBER """\ 重置全域性變數:學生人數STUDENT_NUMBER值 """ def setStudentNumber(num): global STUDENT_NUMBER STUDENT_NUMBER = num """\ 獲取全域性變數:學校名稱SCHOOL_NAME的值 """ def getSchoolName(): return SCHOOL_NAME """\ 重置全域性變數:學校名稱SCHOOL_NAME值 """ def setSchoolName(name): global SCHOOL_NAME SCHOOL_NAME = name def changeValue(): name = '北京大學' number = 90 print('全域性變數STUDENT_NUMBER = ' , getStudentNumber()) print('全域性變數SCHOOL_NAME = ' , getSchoolName()) print('#######################################') print('區域性變數namber = ' , number) print('區域性變數name = ' , name) print('#######################################') print('改變全域性變數值...') print('#######################################') setStudentNumber(number) setSchoolName(name) print('全域性變數STUDENT_NUMBER = ' , getStudentNumber()) print('全域性變數SCHOOL_NAME = ' , getSchoolName()) if __name__ == '__main__': changeValue()