x = int(2.9) # int built-in g_count = 0 # global def outer(): o_count = 1 # enclosing def inner(): i_count = 2 # local
#定义变量a >>> a = 0 >>> print a 0 #定义函数p() >>> def p(): ... print a ... >>> p() 0 #定义函数p2() >>> def p2(): ... print a ... a = 3 ... print a ... >>> p2() # 运行出错,外部变量a先被引用,不能重新赋值 Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<interactive input>", line 2, in p2 UnboundLocalError: local variable 'a' referenced before assignment #定义函数p3() >>> def p3(): ... a = 3 # 不引用直接赋值 ... print a ... >>> p3() 3 >>> print a 0 # 外部变量a并未改变
以上所述是小编给大家介绍的Python中的变量和作用域详解,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对PHP中文网的支持!
更多Python中的变量和作用域相关文章请关注PHP中文网!
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did85935