Created
May 19, 2016 11:00
-
-
Save xujiazhe/9376040db7577ace3fc182981fa98a82 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
# -*- coding:gbk -*- | |
''' | |
原地址 http://www.cnblogs.com/rhcad/archive/2011/12/21/2295507.html | |
可以尝试了解嵌套的装饰器的原理 | |
mylocker.py: 公共类 for 示例9.py 稍稍修改的示例9 | |
''' | |
class mylocker: | |
def __init__(self): | |
print("mylocker.__init__() called.") | |
@staticmethod | |
def acquire(): | |
print("mylocker.acquire() called.") | |
@staticmethod | |
def unlock(): | |
print(" mylocker.unlock() called.") | |
class lockerex(mylocker): | |
@staticmethod | |
def acquire(): | |
print("lockerex.acquire() called.") | |
@staticmethod | |
def unlock(): | |
print(" lockerex.unlock() called.") | |
def lockhelper(cls): | |
'''cls 必须实现acquire和release静态方法''' | |
def _deco(func): | |
def __deco(*args, **kwargs): | |
print("before %s called." % func.__name__) | |
cls.acquire() | |
try: | |
return func(*args, **kwargs) | |
finally: | |
cls.unlock() | |
return __deco | |
return _deco | |
# -*- coding:gbk -*- | |
'''示例9: 装饰器带类参数,并分拆公共类到其他py文件中 | |
同时演示了对一个函数应用多个装饰器''' | |
class example: | |
# @lockhelper(mylocker) | |
def myfunc(self): | |
print(" myfunc() called.") | |
# @lockhelper(mylocker) | |
# @lockhelper(lockerex) | |
def myfunc2(self, a, b): | |
print(" myfunc2() called.") | |
return a + b | |
if __name__=="__main__": | |
a = example() | |
# a.myfunc() | |
# print "\n\n\n" | |
# print(a.myfunc()) | |
# print lockhelper(mylocker)(a.myfunc)() | |
# print "\n\n\n" | |
#print(a.myfunc2(1, 2)) | |
print lockhelper(mylocker)( lockhelper(lockerex)(a.myfunc2) )(1,2) | |
''' | |
before myfunc called. | |
mylocker.acquire() called. | |
myfunc() called. | |
mylocker.unlock() called. | |
None | |
before __deco called. | |
mylocker.acquire() called. | |
before myfunc2 called. | |
lockerex.acquire() called. | |
myfunc2() called. | |
lockerex.unlock() called. | |
mylocker.unlock() called. | |
3 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment