-1

我正在尝试为两个属性重用验证器函数。我知道我可以在外部创建函数并在验证器中引用它,但是像这样堆叠装饰器在技术上是否正确:

In [6]: @attr.s 
   ...: class A: 
   ...:     a = attr.ib() 
   ...:     b = attr.ib() 
   ...:      
   ...:     @a.validator 
   ...:     @b.validator 
   ...:     def a_b_check(self, attribute, value): 
   ...:         assert value == 5 
   ...:                                                                                                                 

In [7]: A(5,5)                                                                                                          
Out[7]: A(a=5, b=5)

In [8]: A(5,6)                                                                                                          
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-8-ec475f254e70> in <module>
----> 1 A(5,6)

<attrs generated init 71300c05faf88cf49c2dcea04f8137146d4dac79> in __init__(self, a, b)
      4     if _config._run_validators is True:
      5         __attr_validator_a(self, __attr_a, self.a)
----> 6         __attr_validator_b(self, __attr_b, self.b)

<ipython-input-6-701125903dd2> in a_b_check(self, attribute, value)
      7     @b.validator
      8     def a_b_check(self, attribute, value):
----> 9         assert value == 5
     10 

AssertionError: 

In [9]: A(6,5)                                                                                                          
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-9-4582d95e8377> in <module>
----> 1 A(6,5)

<attrs generated init 71300c05faf88cf49c2dcea04f8137146d4dac79> in __init__(self, a, b)
      3     self.b = b
      4     if _config._run_validators is True:
----> 5         __attr_validator_a(self, __attr_a, self.a)
      6         __attr_validator_b(self, __attr_b, self.b)

<ipython-input-6-701125903dd2> in a_b_check(self, attribute, value)
      7     @b.validator
      8     def a_b_check(self, attribute, value):
----> 9         assert value == 5
     10 

AssertionError: 

测试表明验证效果很好,但不确定是否发生了问题。

4

1 回答 1

1

我希望它可以正常工作,因为验证器的 @-notation根本不会改变方法,只是记住它

如果你想重用验证器,我建议使用更通用且跨类工作的函数。

于 2019-09-10T16:51:22.403 回答