Python 3.x 无法使用装饰器打印结果
我刚开始学习python,在使用decorator时遇到了一个令人厌倦的问题。我无法从@decorate1打印结果。如果您能帮我解决这个问题,我将不胜感激。请查找以下代码:Python 3.x 无法使用装饰器打印结果,python-3.x,python-2.7,python-decorators,Python 3.x,Python 2.7,Python Decorators,我刚开始学习python,在使用decorator时遇到了一个令人厌倦的问题。我无法从@decorate1打印结果。如果您能帮我解决这个问题,我将不胜感激。请查找以下代码: def decorate1(function): def wrapper(*args): print("the arguments are ",args) return wrapper def fileoperation(function): def wrapper():
def decorate1(function):
def wrapper(*args):
print("the arguments are ",args)
return wrapper
def fileoperation(function):
def wrapper():
f=function()
with open("sample.txt",'w') as wf:
wf.write(f)
return wrapper
def listoperation(function):
def wrapper(*args):
mylst=[]
for i in args:
mylst.append(i)
print(mylst)
return wrapper
@listoperation
@decorate1
def display(name,age):
pass
display('vijay',31)
@fileoperation
def filestring():
return "This is a file"
filestring()
Output:
['vijay', 31]
[Finished in 0.2s]
代码的问题是,装饰程序没有返回包装好的函数 我将举一个例子,排除
filestring()
函数,因为它是相同的错误
def decorate1(function):
def wrapper(*args, **kwargs):
print("the arguments are ",args)
function(*args, **kwargs)
return wrapper
def listoperation(function):
def wrapper(*args, **kwargs):
mylst=[]
for i in args:
mylst.append(i)
print(mylst)
function(*args, **kwargs)
return wrapper
@listoperation
@decorate1
def display(name,age):
pass
display('vijay',31)
正如您所看到的,您的函数中的某些点发生了变化:
- 即使示例中不需要,也更安全的做法是始终构建包装器接受和转发
,因此任何形式的传递参数都将转发给包装函数*args、**kwargs
- 包装器应该调用包装函数及其所有参数:否则将不会执行“包装”函数李>
一般示例: 有时候,一个例子可以帮助你把注意力集中在装饰师身上 假设您想要一个打印第一个
N
自然数的函数:
def my_numbers(N):
return list(range(N))
然后您会注意到,这个函数和其他许多函数有时会失败。您怀疑有人在传递您不期望的参数,因此您希望在不干扰函数的情况下打印正在传递的参数和函数的输出。您编写了一个decorator,但由于所有函数都采用不同数量的参数和键值参数,因此您将其保持为常规:
def my_logger(f):
def wrapper(*args, **kwargs):
print("Someone has passed these arguments: {0}".format(*args))
res = f(*args, **kwargs)
print("With the values that someone passed, I got the following output: {0}".format(res))
return res
return wrapper
在装饰我们的功能之后:
@my_logger
def my_numbers(N):
return list(range(N))
我们得到以下输出:
有人通过了这些论点:4通过某人传递的值,我得到以下输出:[0、1、2、3]
[0,1,2,3]
在装饰前缺少@1