zoukankan      html  css  js  c++  java
  • python装饰器初探

    双层装饰器输出星号、百分号:
     1 #!usr/bin/env/python35
     2 # -*- coding:utf-8 -*-
     3 # author: Keekuun
     4 
     5 import functools
     6 
     7 
     8 def star(func):
     9     @functools.wraps(func)
    10     def wrappers(*args, **kwargs):
    11         print('*'*50)
    12         func(*args, **kwargs)
    13         print('*'*50)
    14     return wrappers
    15 
    16 
    17 def percent(func):
    18     @functools.wraps(func)
    19     def wrappers(*args, **kwargs):
    20         print('%	'*10)
    21         func(*args, **kwargs)
    22         print('%	'*10)
    23         return func
    24     return wrappers
    25 
    26 
    27 @star
    28 @percent
    29 def hello():
    30     print('				hello')
    31 
    32 
    33 hello()
    
    

    能否写出一个@log的decorator,使它既支持:
    @log
    def f():
      pass
    又支持:
    @log('execute')
    def f():
      pass
    还支持:

    @log()
    def f():
      pass

    def log(msg=''):
        def decorator(func):
            @functools.wraps(func)
            def wrapper(*args, **kwargs):
                if isinstance(msg, (int, str)):
                    print(msg)
                else:
                    pass
                func(*args, **kwargs)
            return wrapper
        return decorator if isinstance(msg, (int, str)) else decorator(msg)
    
    
    @log(11)    # int传入
    def hello_world1():
        print('Hello world')
    
    
    @log('hi_11')    # str传入
    def hello_world2():
        print('Hello world')
    
    
    @log()    # ()空
    def hello_world3():
        print('Hello world')
    
    
    @log    #无
    def hello_world4():
        print('Hello world')
    
    
    hello_world1()
    hello_world2()
    hello_world3()
    hello_world4()
    明月装饰了你的窗子,你装饰了他的梦。
  • 相关阅读:
    redis 笔记
    经验
    增加模块-概念图
    node API buffer
    VS2010中使用CL快速 生成DLL的方法
    WIN7下VS2010中使用cl编译的步骤
    Win7下VS2010编译的程序在XP报错:找不到msvcp100d.dll或者msvcp100.dll
    C#速学
    Windows下架设SVN服务
    Redis 压力测试
  • 原文地址:https://www.cnblogs.com/zkkysqs/p/9157594.html
Copyright © 2011-2022 走看看