** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
animal = 'cat'
def f():
print(animal)
f()
result
cat
Since ʻanimal here is a global variable, it can of course be called in f () `.
animal = 'cat'
def f():
animal = 'dog'
print('after:', animal)
f()
result
after: dog
Of course this will output dog, but this does not overwrite the global variable ʻanimal`.
animal = 'cat'
def f():
print(animal)
animal = 'dog'
print('after:', animal)
f()
result
UnboundLocalError: local variable 'animal' referenced before assignment
When I first tried to print ʻanimal`, I got an error.
This is an error that there is a description that declares a local variable in the function and you are trying to print it before it is written.
animal = 'cat'
def f():
# print(animal)
animal = 'dog'
print('local:', animal)
f()
print('global:', animal)
result
local: dog
global: cat
In f (), declare the local variable ʻanimal and print it, The print on the last line prints the global variable ʻanimal.
animal = 'cat'
def f():
global animal
animal = 'dog'
print('local:', animal)
f()
print('global:', animal)
result
local: dog
global: dog
Calling the global variable ʻanimlal by using global` in a function will overwrite that global variable.
animal = 'cat'
def f():
animal = 'dog'
print(locals())
f()
print(globals())
result
{'animal': 'dog'}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fd8f9f687f0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'test.py', '__cached__': None, 'animal': 'cat', 'f': <function f at 0x7fd8f9db9160>}
Local variables and global variables can be called as dictionaries by using locals () and globals ().
If you look at the printed global variables, you can see that there are variables that are defined in advance on the python side.
def TestFunc():
"""Test func doc"""
print(TestFunc.__name__)
print(TestFunc.__doc__)
TestFunc()
print('global:', __name__)
result
TestFunc
Test func doc
global: __main__
If you specify a function name, you can output the __name__ and __doc__ of that function.
Recommended Posts