python basis (IX): function of local and global variables

  • Local variables : declared in a function, not available in other places,
  • Global variables : the external declaration, all functions can be used.

Variable types of global variables:

  • For immutable types of global variables, global need to modify the statement in the function.
  • For variable types of global variables, to modify the function can not use the global statement.

That is, when the global variable is string, int, tuple immutable data type, etc., when the function declared redefined global assignment use; when the global variable is a variable list and dict other type, may be no global declarations.

Example 1 (hard type):

def test():
    a = 2
    print(a)
    print(id(a))
a = 1
test()
print(a)
print(id(a))

'''输出:
2
140734691578720
1
140734691578688
'''

inside and outside a not a value. id () represents the address, apparently, two a different address.

Our global statement inside the function:

def test():
    global a
    a = 2
    print(a)
    print(id(a))
a = 1
test()
print(a)
print(id(a))

'''
输出:
2
140734691578720
2
140734691578720
'''

After the global statement, both inside and outside is a consistent address is the same.

Example 2 (soft type):

def test(a):
    a[0] = 2
    print(a)
    print(id(a))
a = [1, 1]
test(a)
print(a)
print(id(a))
'''
输出:
[2, 1]
3127152186056
[2, 1]
3127152186056
'''

A list of values ​​and addresses are exactly the same.

Guess you like

Origin blog.csdn.net/qq_26271435/article/details/89711572