English 中文(简体)
甲 Python?
原标题:Protected method call in Python?

我有一系列我所需要的呼吁,所有这些呼吁都可以成为一种例外,我希望能很好地保护这些呼吁。 我正设法找到更专业的方法,以在座:

def protected_call(method):
   result = None
   try:
       result= method()
   except:  pass

   return result
class Test():


  def terminate(): 
     protected_call(self.could_throw_exception)
     protected_call(self.receiver.stop)
     protected_call(self.connection.stop)
     #etc

是否有更好的办法这样做? 或许有说明?

为了澄清,Idont希望就原始方法说明:

class Receiver():
  @protected
  def stop():
     print  I dont want to do this 

class Test():
  @protected
  def could_throw_exception():
     print  dont want this 
  def stop(): 
     self.could_throw_exception()
     self.receiver.stop()

这正是:

class Receiver():
  def stop():
     print  I want this 

class Test():

  def could_throw_exception():
     print  like this 

     This one cares about crashing   
  def stop()
     self.could_throw_exception()
     self.receiver.stop()
     self.connection.stop()

     This one does not   
  def terminate(): 
     #i want to define it at the call level.
     @protected
     self.could_throw_exception()
     @protected
     self.receiver.stop()
最佳回答

正如Nmichaels所建议的那样,这类事情最好通过 声明处理。

@contextlib.contextmanager
def suppress_exceptions(*exceptions):
    if not exceptions:
        exceptions = Exception
    try:
        yield
    except exceptions:
        # You would log an error here
        # If you have logging in your application
        pass

with suppress_exceptions():
    1/0

print("Ignored the exception!")

with suppress_exceptions(IOError):
    1/0

# The second one will let the exception through
问题回答

因此,决定者是完美的:

def protected_call(method):
    def wrapper(*args, **kwargs):
        try:
            return method(*args, **kwargs)
        except:
            pass
    return wrapper

样本使用:

@protected_call
def foo():
    raise Exception()

# nothing is being raised
foo()

象一名矫正员那样做

def protected_call(func):
    def inner(*args, **kw):
        try:
            return func(*args, **kw)
    except:
            pass
    return inner

class Test():

    @protected_call
    def throws_exception(self):
        print 1/0

    @protected_call
    def no_exception(self):
        print 4

    def sometimes_need_exception(self):
        print 5
    protected_sometimes_need_exception = protected_call(sometimes_need_exception)

    def stop(self):
        self.throws_exception()
    self.no_exception()

至少伐木例外似乎是一个有用的特点,或者你如何控制意外错误?





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签