Saturday, January 8, 2011

IDisposable+Using keyword in Python

In Python the keyword with match the C# keyword using. The method __exit__() match the method Dispose(). But a method __enter__() is required. The __enter__() simply returns the instance itself.

class  MyClass: 
      def  __init__( self): 
         print  "Initializing..." 
      def  __enter__( self): 
         print  "Entering..." 
         return  self
      def  __exit__( self,  type,  value,  traceback): 
         print  "Exiting..." 
         return  False # Do not swallow raised exception 
      def  Run( self): 
         print  "Running" 
 def  Main(): 
      with  MyClass()  as  e: 
         e. Run() 

No comments:

Post a Comment