检查实例变量的方法装饰器

Decorator on methods checking for instance variable

我有一个pythonclass,Something。我想创建一个方法 borrowed,它会检查 Something 的实例变量 blue 是否为 None.

如何在实例方法上创建 @check_none 以便它检查实例变量?在装饰器函数中使用 self 无效 ;(

示例:

def check_token(func):
    def inner(*args, **kwargs):
        if self.token == None:
            raise ValueError
        else:
            return func(*args, **kwargs)
    return inner

class Something(object):
   def __init__(self, token=None):
      self.token = token

   @check_token
   def testfunction(self):
      print "Test"

产生 global name 'self' is not defined 错误。

您的内部函数没有 self 参数;添加并传递:

def check_token(func):
    def inner(self, *args, **kwargs):
        if self.token is None:
            raise ValueError
        else:
            return func(self, *args, **kwargs)
    return inner

inner 函数在修饰时替换了原始方法,并在相同的 self 参数中传递。

或者,您可以使用 args[0].token,因为 self 只是第一个位置参数。

请注意,我用推荐的 is None 测试替换了您的 == None 测试。

演示:

>>> def check_token(func):
...     def inner(self, *args, **kwargs):
...         if self.token is None:
...             raise ValueError
...         else:
...             return func(self, *args, **kwargs)
...     return inner
... 
>>> class Something(object):
...    def __init__(self, token=None):
...       self.token = token
...    @check_token
...    def testfunction(self):
...       print "Test"
... 
>>> Something().testfunction()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in inner
ValueError
>>> Something('token').testfunction()
Test