从装饰器访问 self
在unittest的setUp()方法中,我设置了一些self变量,这些变量稍后在实际测试中引用。我还创建了一个装饰器来进行一些日志记录。有没有办法可以从装饰器访问这些 self 变量?
为了简单起见,我发布了这段代码:
def decorator(func):
def _decorator(*args, **kwargs):
# access a from TestSample
func(*args, **kwargs)
return _decorator
class TestSample(unittest.TestCase):
def setUp(self):
self.a = 10
def tearDown(self):
# tear down code
@decorator
def test_a(self):
# testing code goes here
What would be the best way of accessing a (setUp()) fromdecorator?
In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator?
For the sake of simplicity, I'm posting this code:
def decorator(func):
def _decorator(*args, **kwargs):
# access a from TestSample
func(*args, **kwargs)
return _decorator
class TestSample(unittest.TestCase):
def setUp(self):
self.a = 10
def tearDown(self):
# tear down code
@decorator
def test_a(self):
# testing code goes here
What would be the best way of accessing a (set in setUp()) from decorator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您正在装饰一个方法,并且
self
是一个方法参数,因此您的装饰器可以在运行时访问self
。显然不是在解析时,因为还没有对象,只是一个类。所以你将你的装饰器更改为:
Since you're decorating a method, and
self
is a method argument, your decorator has access toself
at runtime. Obviously not at parsetime, because there are no objects yet, just a class.So you change your decorator to:
您实际上也可以使用
functools.wraps
< /a> 保存help(obj.method)
信息。除此之外,如果装饰器仅在类中使用,则可以将其包含在类主体中:其工作原理如下
,并且在调用 help() 时将打印原始文档字符串:
而不是这样(当省略
@ 时)包裹(func)
):You could actually also use
functools.wraps
to save thehelp(obj.method)
information. In addition to that, if the decorator is only used in the class, it could be included to the class body:Which works like this
and will print the original docstring when calling help():
instead of this (when omitting
@wraps(func)
):如果您使用基于类的装饰器实现,这里有一个示例。
我个人不喜欢在这种情况下使用 self 作为变量名来引用原始调用者。它可能会产生可读性问题。相反,使用不同的唯一名称来调用它(在本例中,我使用 -
calling_instance
)用法如下:
SomeOtherClass
的batch_id
属性是现在可以从装饰器访问。If you are using class based decorator implementation., here is an example.
I personally don't like using
self
as the variable name in this context for referring the original caller. It might create readability issue. Instead call it with a different unique name ( in this example, I used -calling_instance
)Usage would be like :
The
batch_id
property ofSomeOtherClass
is now accessible from decorator.