打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
自动为py类的每个方法添加装饰器
'''Add decorator for each method of a class.'''
import functools
import threading
class DecorateClass(object):
    def decorate(self):
        for name, fn in self.iter():
            if callable(fn):
                self.operate(name, fn)
class LockerDecorator(DecorateClass):
    def __init__(self, obj, lock=threading.RLock()):
        self.obj = obj
        self.lock = lock
    def iter(self):
        return [(name,getattr(self.obj, name)) \
                for name in dir(self.obj) if not name.startswith('_')]
     
    def operate(self, name, fn):
        @functools.wraps(fn)
        def locker(*args,**kv):
            self.lock.acquire()
            try:
                return fn(*args, **kv)
            finally:
                self.lock.release()
        setattr(self.obj, name, locker)
class mylocker:
    def __init__(self):
        print("mylocker.__init__() called.")
    def acquire(self):
        print("mylocker.acquire() called.")
    def release(self):
        print("  mylocker.unlock() called.")
class Foo(object):
    def __init__(self):
        # Enable one or more decorators for each method:
        LockerDecorator(self).decorate()
        LockerDecorator(self, mylocker()).decorate()
         
    def interface1(self):
        print(" interface1() called.")
    def interface2(self):
        print(" interface2() called.")
    def _interface3(self):
        print("_interface3() called.")
if __name__=="__main__":
    obj = Foo()
    obj.interface1()
    obj.interface2()
    obj.interface1()
    obj.interface2()
    obj._interface3()
    print(obj.interface1.__name__)
    '''
    print(dir(obj))
    print("---------------------")
    for item in [(name,getattr(obj, name)) for name in dir(obj)]:
        print(item)'''
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Python和Decorator(装饰器)模式
Python面向对象特征总结
10个Python面试常问的问题
Python 高级编程之面向切面编程 AOP(二)
面向对象
英伟达小姐姐的Python隐藏技巧合集,推特2400赞,代码可以直接跑 栗子 发自 凹非寺 量子位 ...
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服