【发布时间】:2019-08-27 06:27:07
【问题描述】:
我正在尝试制作两个带参数的装饰器。 First 创建一个带有元素 x 的 list 并调用 func。 second 只是通过从 dict 传递参数来调用 first。
def first(x=1):
def wrapped(func):
l = [x]
func(l)
print(l)
return wrapped
def second(d={'x':10}):
return first(x=d['x'])
third 函数只是修改传入的列表。
我想通过简单地调用third() 来使以下四个装饰器中的任何一个成为可能。我应该如何修改我的代码?
##@second
##@second({'x':100})
##@first
##@first(x=10)
def third(l):
l.append(-1)
third()
例如:
## With @first,
## I am expecting to get [1, -1].
## With @first(x=10),
## I am expecting to get [10, -1].
## With @second,
## I am expecting to get [10, -1].
## With @second({x:100}),
## I am expecting to get [100, -1].
上面的代码是我的问题的抽象。我真正的问题是我想要一个为我处理打开和关闭连接的装饰器,这样我只需要编写处理连接的代码。
而连接需要参数,即first。我希望以不同的方式传递参数,即second。 third 是我要处理的连接。我希望 third 像普通函数一样被调用,它还使用装饰器处理打开和关闭连接。对不起,如果不应该这样使用装饰器,但我真的很想练习使用它。
---更新---
我想要实现的基本如下:
def context_manager(username='user', password='password'):
conn = OpenConnection()
func(conn)
CloseConnection()
def context_manager2(d={'username': 'user', 'password': 'password'}):
content_manager(username=d['username'], password=d['password'])
# @context_manager
# @context_manager('username', '123456')
# @context_manager2
# @context_manager2(d={'username': 'username', 'password': '123456'})
def execute(conn):
pass
我想让四个装饰器中的任何一个成为可能,并且仍然能够以execute() 之类的方式调用execute
【问题讨论】:
-
这不是关于如何修改代码,而是关于装饰器如何工作。
@decorator def function():...与function = decorator(function)相同,所以decorator必须接受一个函数。此外,second中的func是什么?此名称未定义。 -
不清楚您要做什么。你能给出一个示例输出吗?
-
@ForceBru 如有任何混淆,我们深表歉意。我正在随机尝试让事情正常运行...我忘了删除它。
-
@AdamSmith 对不起。我已经更新了我的帖子。