Check condition before method call

I have a class called Server that you can start and stop. Some methods should not be called if the server is not running, in which case a NotConnectedException should be thrown. Is there a way to call a method before each method in the class and determine if the _started class variable is set to True?

I tried using a decorator, but the decorator function does not have access to the class variable. I tried to do something like this:

class Server(object):
    _started = False
    def started(self):
        if(self._started == False):
            raise NotConnectedException

    @started
    def doServerAction(self):
       ...
+5
source share
1 answer

Remember which decorators:

@decorate
def foo(...):
    ...

exactly equivalent to:

def foo(...):
    ...
foo = decorate(foo)

, self . , , , , , . started AttributeError, _started , None, None, , , .

, :

import functools

def started(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        if not self._started:
            raise ...
        else:
            return func(self, *args, **kwargs)
    return wrapper

​​; , , - "" , . functools.wraps - , - ; wrapper docstring , "" .

, .

+8

All Articles