简体   繁体   English

在Python装饰器中获取类

[英]Get class in Python decorator

In this code: 在这段代码中:

def online_only(func, self):
    def f(*args, **kwargs):
        if self.running:
            return func(*args, **kwargs)
        else:
            return False
    return f
class VM(object):
   @property
   def running(self):
       return True
   @property
   @online_only
   def diskinfo(self):
       return True

I want diskinfo to run only when VM.running returned True. 我希望diskinfo只在VM.running返回True时运行。 How can I get online_only to be able to read self.running? 如何才能通过online_only阅读self.running?

self is passed as the first parameter to the wrapping function, so just treat the first parameter specially in f : self作为第一个参数传递给包装函数,所以只需要在f处理第一个参数:

def online_only(func):
    def f(self, *args, **kwargs):
        if self.running:
            return func(self, *args, **kwargs)
        else:
            return False
    return f
  1. You can not have two arguments in def online_only(func, self) ? 你不能在def online_only(func, self)有两个参数? it will raise TypeError, so change it to def online_only(func) 它会引发TypeError,因此将其更改为def online_only(func)
  2. The first argument to wrapped function would be self, you can just use that eg 包装函数的第一个参数是self,你可以使用它,例如

def online_only(func):
    def f(self):
        if self.running:
            return func(self)
        else:
            return False
    return f

class VM(object):
    @property
    def running(self):
        return True

    @property
    @online_only
    def diskinfo(self):
        return True

print VM().diskinfo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM