Python 之 global用法

Python 之 global用法

 

废话不说,直接看代码

代码1

# coding: utf-8

age = 18


def happy_birthday():
    print "age {}, happy birthday ~".format(age)

happy_birthday()

print "your age is {}".format(age)

输出结果:

age 18, happy birthday ~
your age is 18

Process finished with exit code 0

输出和谐,没有什么问题。但是当我们想要在happy_birtyday()方法中,给age增加1岁时,竟然出错了

代码2

# coding: utf-8

age = 18


def happy_birthday():
    print "age {}, happy birthday ~".format(age)
    age += 1

happy_birthday()

print "your age is {}".format(age)

 

输出结果:

Traceback (most recent call last):
  File "temp.py", line 10, in 
    happy_birthday()
  File "temp.py", line 7, in happy_birthday
    print "age {}, happy birthday ~".format(age)
UnboundLocalError: local variable 'age' referenced before assignment

Process finished with exit code 1

输出错误:age参数没有定义。很难理解,在代码1中发现成功引用函数外部的全局变量age。但是在代码2中尝试修改age时报错age未定义。这个错误跟python的弱类型有关。具体原因先放一放,遇到这种情况,可以使用global指令解决

代码3

# coding: utf-8

age = 18


def happy_birthday():
    global age
    print "age {}, happy birthday ~".format(age)
    age += 1

happy_birthday()

print "your age is {}".format(age)

输出结果:

age 18, happy birthday ~
your age is 19

Process finished with exit code 0

 

稍微总结一下:

       global参数指定参数来源于global域,指定后可以读取/修改global域参数。如果不指定global,只能引用global参数,不能修改

 

你可能感兴趣的:(python,未解之谜)