Python note 20-adorners, scopes

Source: Internet
Author: User

Scope  of the function
is the nearest principle, look out from inside, if you have in your function, take it.
If you do not have a function inside of it, go to its parent function inside find, father can't use son, son can use father's
function is executed only if it is called
# name = ' python '
# def Warpper (): #1
# name= ' Tuiwu '
# def deco (): #2
# name = ' Chen Winter Melon '
# def HHH (): #3
# name = ' Zhang Ying '
# print (' xxx%s '%name)
# print (' I'm inside%s '%name)
# HHH ()
# deco ()
# Print (' name outside ' is%s '%name)
# warpper ()

Decorative Device
#1, functions can also be nested within the definition of a function
#2, higher order functions
#装饰器说白了就是函数嵌套 + higher order functions
#装饰器的作用就是在不改变原有函数的调用方式, add a new function to the function in the case of a parameter
#偷偷摸摸的给函数加上新功能, but does not change the original function
#常用模块
#什么是模块, the module is actually a python file
Import Time,os,sys
def timer (func):
def deco (*args,**kwargs):
#*args,**kwargs The parameters used to receive incoming functions
start_time = Time.time ()
res = func (*args,**kwargs) #获取返回值
end_time = Time.time ()
print (' Runtime ', end_time-start_time)
return res
return deco

@timer #run = timer (run)
def run ():
# start_time = Time.time ()
print (' run.. ')
Time.sleep (2)
# end_time = Time.time ()
# Print (' Runtime ', end_time-start_time)
#run = = Deco,
@timer
def run2 (name):
print (name)
Time.sleep (0.5)
run2 (' Niuhanyang ')

#上面这个函数其实就是返回了一个函数名而已
#1, call the timer function, to pass in a method name,
# The Timer function defines a function inside a function called Deco
#又在函数deco内部调用了timer里面传入的方法
#run保存的是deco, Deco is a function that calls run to call the Deco

Python note 20-adorners, scopes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.