设计一个装饰器来在文本文件中写入函数返回值

时间:2017-11-24 09:55:41

标签: python python-2.7 python-decorators

装饰者应该像

@log_message
def a_function_that_returns_a_string():
    return "a string"
@log_message
def a_function_that_returns_a_strings_with_a_newline(s):
    return "{}\n".format(s)

我的实现是这样的,但不是在文件中写任何东西,我是装饰者的新手

 def log_message(func):
          def wrapper(*args, **kwargs):
              result = func(a)
              with open('test.txt', 'w') as f:
                 for row in results:
                     f.write("%s\n" % str(row))
              return result
          return wrapper

1 个答案:

答案 0 :(得分:2)

你离我不远: result = func(a)需要result = func(*args, **kwargs)

打印到屏幕。写入文件几乎是一样的:

def log_message(func):

    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        print(result)
        return result

    return wrapper


@log_message
def a_function_that_returns_a_string():
    return "a string"

@log_message
def a_function_that_returns_a_strings_with_a_newline(s):
    return "{}\n".format(s)


a = a_function_that_returns_a_string()
b = a_function_that_returns_a_strings_with_a_newline('abc')