【问题标题】:Decorator on methods checking for instance variable检查实例变量的方法的装饰器
【发布时间】:2015-04-18 07:22:42
【问题描述】:

我有一个 python 类,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 添加到inner() 函数签名中。不要忘记在func() 调用中传递它。或者,使用self = args[0]

标签: python oop python-2.7 decorator python-decorators


【解决方案1】:

您的内部函数没有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 只是第一个位置参数。

请注意,我将您的 == None 测试替换为推荐的 is 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

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2020-07-08
    • 2013-02-12
    • 1970-01-01
    • 2020-01-30
    • 2019-02-03
    相关资源
    最近更新 更多