再谈变量作用域与变量引用
module3.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
var = 'var_in_module3'
module2.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'shouke'
from module3 import var
class ClassOne:
var = 'global var in ClassOne' # 类中的全局变量
def func(self):
print('var in func for ClassOne: %s'% var)#引用module3.var
ClassOne.var = 'var whose value changed in func of ClassOne'
module1.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ ='shouke'
frommodule3importvar
frommodule2importClassOne
deffunction():
print('var in function: %s'% var) #引用module3.var
var1 ='value_for_var1'
if True:
print('var1 in if: %s'% var1)
var1 ='value_changed_for_var1'
print('var1 in if: %s'% var1)
print('var1 out of if: %s'% var1)
print('\nbegan for loop\n')
fornuminrange(1,2):
var1 ='var1_in_for_loop'
if True:
print('var1 in if for loop: %s'% var1)
var1 ='value_changed for var1 in if for_loop'
print('var1 in if for loop: %s'% var1)
print('var1 out of if for loop: %s'% var1)
print('var1 out of for loop: %s'% var1)
classClassTwo:
deffunc(self):
var = ClassOne.var #引用值
print('var in func of ClassTwo: %s'% var)
def func2(self):
ClassOne.var = 'value changed in ClassTwo' #修改值
if__name__ =='__main__':
function()
print('\n')
obj1 = ClassTwo()
obj1.func()
obj2 = ClassOne()
obj2.func()
print('\n')
obj2.func()
obj1.func()
print('\n')
obj1.func2()
obj2.func2()
输出:
说明:
1、如何在不同模块中引用同一个变量?
答案:在一个模块中定义一个全局变量并赋值,然后在其它模块中通过导入定义的变量,在适当的位置引用该变量,如上例中,在module3中定义一个变量,然后通过语句frommodule3 import var导入变量
2、如何在类中定义一个全局变量?
答案:
class ClassName:
var_name = xxxxxxxx
在其它模块中,通过导入该类,然后通过ClassName.var_name方式引用变量,或者给变量赋值。
3、try……except,if,for,while子句中的变量作用域与赋值
举例说明