程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python series - scope details

編輯:Python
  • python_scope
import builtins
# Overview and application of scope
global_scope = 0 # Global scope
# Define a local scope in a closure function
def outer():
o_count = 1 # In a function other than a closure function , Relative to the function inner() Come on Scope nonlocal
def inner():
local_scope = 2 # Local scope
# Check which variables are introduced into the module
print('builtins The variables introduced in the module are :%s' %dir(builtins))
# # Variable access in other modules
name1 = 'SuSan'
if('SuSan'.__eq__(name1)):
result = 'I am SuSan,I am from China'
else:
result = 'I am from USA'
print(result)
# If you define a variable inside a function , Then the external cannot access
def names():
name2 = 'SuSan'
# if('SuSan'.__eq__(name2)):
result1 = 'I am '+name2 +','+'I am from China'
# else:
result1 = 'I am from USA'
# print(result1)
# Global and local variables
total = 0 # This is a global variable
# Function description
def sum(arg1, arg2):
# return 2 The sum of parameters ."
total = arg1 + arg2 # total Here is the local variable .
print(" Function is a local variable : ", total)
return total
# call sum function , The calculation result of the passed in parameter shows the local variable
sum(10, 20)
print(" Outside the function is the global variable : ", total)
# Use golbal Keyword to access and modify global variables
num = 1
def fun1():
# Declare access to global variables
global num # Need to use global Keyword declaration
# Output the original value of the global variable
print(num)
# Modify global variables
num = 123
print(num)
# Call function
fun1()
# Output the modified global variable value
print(num)
# Use nonlocal Keyword to declare variables and modify
# Defined function
def outer():
# Defining variables
num = 10
# Defining nested functions
def inner():
nonlocal num # nonlocal Keyword declaration , Using variables in functions
# Change the value of the variable
num = 100
print(num)
inner()
print(num)
outer()
# Under special circumstances
b = 8
def test(b):
b = b * 10
print(b)
test(b)
b = 8
def test():
global b
b = b * 30
print(b)
test()

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved