Discuss / Python / 这个练习有点难,花了不少时间

这个练习有点难,花了不少时间

Topic source

米粽粽

#1 Created at ... [Delete] [Delete and Lock User]
import functools

def log(arg):
  if isinstance(arg, str):
    def decorator(fn):
      @functools.wraps(fn)
      def wrapper(*args, **kw):
        print(arg)
        print('begin call')
        fn(*args, **kw)
        print('end call')
      return wrapper
    return decorator
  else:
    @functools.wraps(arg)
    def wrapper(*args, **kw):
      print('begin call')
      arg(*args, **kw)
      print('end call')
    return wrapper

@log
def f1(t):
  print(t)

@log('execute')
def f2(t):
  print(t)

米粽粽

#2 Created at ... [Delete] [Delete and Lock User]

在 StackOverflow 还看到可以用 if hasattr(arg, '__call__'): 来判断

米粽粽

#3 Created at ... [Delete] [Delete and Lock User]

还可以 if callable(arg):

米粽粽

#4 Created at ... [Delete] [Delete and Lock User]

这个用法似乎争论不小,原帖见 StackOverflow

请问博主觉得在装饰器的使用场景下,下面哪种是最合适的选择?

  • type(arg) == types.FunctionType
  • callable(arg)
  • hasattr(arg, '__call__')

  • 1

Reply