python - Check condition before method call -


i have class named server can started , stopped. methods should not called unless server started, in case notconnectedexception should raised. there way call method before every method in class , determine if class variable _started set true?

i tried using decorator, decorator function not have access class variable. trying this:

class server(object):     _started = false     def started(self):         if(self._started == false):             raise notconnectedexception      @started     def doserveraction(self):        ... 

remember decorators are:

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

is equivalent to:

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

the decorator called on function, calling first parameter self makes no sense. also, decorator called on function when defined, , whatever returns used in place of function. if started decorator didn't throw attributeerror trying access _started attribute of function, return none, making methods set none, , not callable.

what want this:

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 

almost decorators of form; take function, create wrapper "around" received function, , return wrapper. use of functools.wraps here convenience if ever end working code in interactive interpreter session; automatically updates wrapper function name , docstring of original function, makes decorated functions "look like" original function bit more.

it's irrelevant whether defined inside class or not.


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -