如何在Python中访问decorator中的类属性?
我正在尝试使用参数化的如何在Python中访问decorator中的类属性?,python,nose,nosetests,parameterized-unit-test,nose-parameterized,Python,Nose,Nosetests,Parameterized Unit Test,Nose Parameterized,我正在尝试使用参数化的nose\u测试,并希望将其用于unittest方法 from nose.tools import assert_equal from nose_parameterized import parameterized import unittest Class TestFoo(unittest.TestCase): def setUp(self): self.user1 = "Bar" self.user2 = "Fo
nose\u
测试,并希望将其用于unittest方法
from nose.tools import assert_equal
from nose_parameterized import parameterized
import unittest
Class TestFoo(unittest.TestCase):
def setUp(self):
self.user1 = "Bar"
self.user2 = "Foo"
@parameterized.expand([
("testuser1",self.user1,"Bar"),
("testuser2",self.user2,"Foo")
]
def test_param(self,name,input,expected):
assert_equal(input,expected)
但是,
self
未在decorator函数中定义。有解决办法吗?我知道我可以使用全局类变量,但我需要在设置中使用变量
当您似乎认为decorator将运行时,decorator没有运行。在以下示例中:
class spam:
@eggs
def beans( self ):
pass
记住,decorator的用法与所说的相同:
beans = eggs( beans )
在spam
范围内,执行def
语句本身之后立即执行。何时执行def
语句?在定义类及其方法时。修饰符修改方法spam.beans
的类级定义,而不是self.beans
的实例级值。当然,这发生在该类的任何实例被创建之前很久,也就是说,在对任何一个特定实例的引用,self
有意义之前
如果您想将特定的可调用函数(例如,修改后的test\u param
可调用函数,其中使用了某些预烘焙参数)附加到实例self
,您当然可以在一个实例方法(例如\u init\u
或setUp
)中执行此操作
有些人将类定义代码描述为发生在“解析时”,实例级代码描述为发生在“运行时”。尽管Python中几乎所有内容都是“运行时”的,但您可能会发现这是一种有用的思考方法,也可能不会发现。一种解决方法是在decorator中使用包含属性名称的字符串,在test函数中使用
getattr
:
@parameterized.expand([
("testuser1", "user1", "Bar"),
("testuser2", "user2", "Foo")
])
def test_param(self, name, input, expected):
assert_equal(getattr(self, input), expected)
使用这种方法,
test_param
假设其输入
参数的值是属性名,其值应与预期的
相关:和进行检查,OP代码中对self.user1
和self.user2
的赋值应该修改为发生在\uuuuu init\uuuuuuuuuuuuuuuuuuself(self)
内部,或者user1
和user2
应该成为类属性。在后一种情况下,您的代码必须成为getattr(TestFoo,input)
,但我假设OP想要前者(否则为什么不将input
值“Foo”和“Bar”硬编码到装饰器中)。@jez我相信这是可行的self.user1
和self.user2
是在每次测试前运行的setUp
方法中分配的。啊,我明白了,那么这只是OP代码中setUp
之前缺少关键字def
的情况。