Skip to main content
 首页 » 编程设计

python之Python 中 protected 方法调用

2025年05月04日14bluestorm

我需要进行一系列调用,所有这些调用都可能引发异常,我想要一种保护调用的好方法。我试图找到一种更专业的方法来在 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 

有更好的方法吗?也许有注释?

澄清一下,我不想在原始方法上添加注释,即:

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 所建议的,这种事情最好通过 with 语句来处理。

@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