简体   繁体   English

Python方法装饰器来访问实例变量

[英]Python method decorator to access an instance variable

I have a Python class that has a couple of state variables - let's call them self.state and self.process : 我有一个带有几个状态变量的Python类-我们将它们self.stateself.process

class MyClass(object):
    def __init__(state=None, process=None):
        self.state = state
        self.process = process

Now, I have a LOT of methods that should yield an error if self.state and self.process are none. 现在,我有很多方法,如果self.stateself.process存在,则应该产生错误。 I don't want to have to handcode a test for each, so I was thinking, I'll do a decorator - something like this: 我不想为每个测试手动编写代码,所以我在想,我会做一个装饰器-像这样:

class MyClass(object):
    ...

    @needs_state
    def some_function():
        # do something

Now if some_function() is called but self.state is None , an error will be raised. 现在,如果调用some_function()self.stateNone ,将引发错误。 Can I accomplish this with decorators - ideally just with one? 我可以用装饰器完成此操作吗?理想情况下,只用一个装饰器即可完成此操作吗? (I've seen the solution that uses a class decorator and I'm not sure it does what I wish it did!). (我已经看到了使用类装饰器的解决方案,但我不确定它是否可以实现我希望的效果!)。 Bonus points for a good explanation for why I cannot ;) 奖励积分为为什么我不能做一个很好的解释;)

Yeah, decorators are ordinary functions, so self is no exception to the rule. 是的,装饰器是普通函数,因此self也不例外。 So let's say I write a decorator function that takes an argument called self : 假设我编写了一个装饰器函数,该函数接受一个名为self的参数:

def needs_state(fn):
    def decorator(self, *args, **kwargs):
        if self.state is None:
            raise ValueError('Oh no')
        return fn(self, *args, **kwargs)
    return decorator

It does not know what self is, because it is not in a class, but that's okay, you can use the decorator in a class, in the way you expect. 它不知道self是什么,因为它不在类中,但是没关系,您可以按期望的方式在类中使用装饰器。

class MyClass(object):

    def __init__(self, state=None):
        self.state = state

    @needs_state
    def some_function(self):
        print self.state

So, if you now instantiate the class with anything, your some_function will first check if self.state is none, because you had just decorated it. 因此,如果现在使用任何实例化该类,则some_function将首先检查self.state是否为none,因为您刚刚装饰了它。 Similarly, if the class does not have a state, then the exception is raised as expected. 同样,如果类没有状态,则按预期引发异常。

MyClass(1).some_function()  # 1
MyClass(None).some_function()  # raises

self.process is left out so you need to do some work. self.process被遗漏了,所以您需要做一些工作。

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

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