开发者

Get class in Python decorator

开发者 https://www.devze.com 2022-12-21 07:18 出处:网络
In this code: def online_only(func, self): def f(*args, **kwargs): if self.running: return func(*args, **kwargs)

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

   @propert开发者_StackOverflow中文版y
   @online_only
   def diskinfo(self):
       return True

I want diskinfo to run only when VM.running returned True. How can I get online_only to be able to read self.running?


self is passed as the first parameter to the wrapping function, so just treat the first parameter specially in 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) ? it will raise TypeError, so change it to def online_only(func)
  2. The first argument to wrapped function would be self, you can just use that e.g.

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号