首页 > python3 decorator 求助

python3 decorator 求助

#! python

def logger(func):
    def inner(*args, **kwargs):
        print("Arguments are : %s, %s" % args, kwargs)
        return func(*args, **kwargs)
    return inner

@logger
def foo1(x, y=1):
    return x*y

@logger
def foo2():
    return 2

foo1(5, 4)
foo1(3, y="alex")
foo2()

出错是:

Arguments are : 5, 4 {}
Traceback (most recent call last):
File ".\decorator.py", line 18, in
foo1(3, y="alex")
File ".\decorator.py", line 5, in inner
print("Arguments are : %s, %s" % args, kwargs)
TypeError: not enough arguments for format string

我用的python是3.4.0


这个其实跟 python 3 和 decorator 关系都不太大,是因为 print 用法有些错误,应该写作如下形式,注意括号。

print("Arguments are : %s, %s" % (args, kwargs))

自己找到了答案,原来print函数百分号后面的要使用tuple, 应该是下面这样才对。
print("Arguments are : %s, %s" % (args, kwargs) )

另外,查到说现在百分号的形式不太使用了,应该用
print("Arguments are : {0}, {1}".format(str(args), str(kwargs)) )
更好

【热门文章】
【热门文章】