Last active
September 11, 2016 23:13
-
-
Save Svtter/9e5c8dd980b3557dc6231acbb991103f to your computer and use it in GitHub Desktop.
Python装饰器示例代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 就像是env Python那样的美丽。 | |
# coding: utf-8 | |
''' | |
闭包的概念: | |
内部函数中对enclosing作用域的变量进行引用 | |
''' | |
def func_150(val): | |
passline = 90 | |
# 打印val的地址 | |
print ("Val id is %x" % id(val)) | |
passline = 90 | |
if val >= passline: | |
print ('%d pass' % val) | |
else: | |
print ('failed') | |
def func_100(val): | |
passline = 60 | |
# 打印val的地址 | |
print ("Val id is %x" % id(val)) | |
if val >= passline: | |
print ('%d pass' % val) | |
else: | |
print ('failed') | |
# def in_func(): #(val,) val会被添加进来 | |
# print (val) | |
# in_func() | |
# return in_func | |
def Max(val1, val2): | |
return max(val1, val2) | |
# f = func(89) | |
# f() # in_func | |
# print(Max(90, 100)) | |
# print (f.__closure__) | |
func_150(89) | |
func_100(89) | |
print('-------------------------------') | |
# 有没有一种方式? | |
def set_passline(passline): # passline = 60 | |
# print ("%x" % id(passline)) | |
def cmp(val): # passline 添加到clojure属性中 | |
if val >= passline: | |
print ('Pass') | |
else: | |
print ('Failed') | |
return cmp | |
f_100 = set_passline(60) | |
print (type(f_100)) | |
print (f_100.__closure__) | |
f_100(89) | |
# f_100(59) | |
f_150 = set_passline(90) | |
# print (type(f_150)) | |
# print (f_150.__closure__) | |
f_150(89) | |
# 以上就是闭包的优越性 | |
''' | |
1. 封装 | |
2. 复用 | |
''' | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
""" | |
""" | |
def deco(func): | |
def in_deco(x, y): | |
print ('in deco') | |
func(x, y) | |
print ('cal deco') | |
return in_deco | |
# deco(bar) -> in_deco | |
# bar = in_deco | |
# bar() in_deco() | |
@deco | |
def bar(x, y): | |
print ('in bar', x + y) | |
print (type(bar)) | |
bar(1, 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment