day11 namespace scope
A. Ternary operator
def func(a, b):
return a if a > b else b
print(func(44,66))
II: Function Comment
def func(a, b):
'''
This function is used to calculate a and b and
: A param: a first data
: Param b: second data
: Return: the return of two numbers
'''
return a + b
print (func .__ doc__) #document documents
III. Namespace (namespace)
Built-in namespace: Store provides us with the name python
Global namespace: py file, outside of the function variables
Local namespace: py file, variable within the function
a = 10
def fn (): # fn are global name space, it is considered the top grid write it is global
b = 20 # variable b only when the function is called, it will be used
print(a)
def gn():
print(a)
fn()
gn()
Load order # namespaces: Built-in -> Global -> Local
Four Scope: is the scope, range divided by effective
Global Scope: Global and built
The local scope: local
Global () Local ()
a = 10
def fn():
b = 20
def in ():
c = 30
print (globals ()) # can view the contents of global scope
Scope print (locals ()) # View the current scope of content, and locals () where the relationship
a = 10
def fn():
b = 20
def in ():
print (globals ()) #en not called, print is not performed, fn () No results
print(locals())
fn()
V. nested functions
def outer():
print('i am in outer')
def inner():
print('i am in inner') #可以无限的往下套
inner()
outer()
六.global和nonlocal关键字
global 改全局
a = 10 #全局变量本身不安全, 不能随意修改(闭包可解决此事)
def func():
global a #不写global, 可以使用a, 但是不能改a 的值, 否则报错
a = 20 #在调用func()之后, 1.把全局的a 改成 20 2.创建全局变量 a
func()
print(a)
nonlocal 改上一层,还要有这个变量, 若没有,再往上找, 直到找最后一层, 找不到报错(但是不找全局)
a = 30
def outer():
a = 10 #找的这个,没有则报错
def inner():
nonlocal a
a = 20
inner()
print(a)
outer()
print(a) #全局的不找