subclassing file objects (to extend open and close operations) in python 3

前端 未结 3 1888
北恋
北恋 2020-12-07 00:36

Suppose I want to extend the built-in file abstraction with extra operations at open and close time. In Python 2.7 this works:

cla         


        
3条回答
  •  旧巷少年郎
    2020-12-07 00:55

    You could just use a context manager instead. For example this one:

    class SpecialFileOpener:
        def __init__ (self, fileName, someOtherParameter):
            self.f = open(fileName)
            # do more stuff
            print(someOtherParameter)
        def __enter__ (self):
            return self.f
        def __exit__ (self, exc_type, exc_value, traceback):
            self.f.close()
            # do more stuff
            print('Everything is over.')
    

    Then you can use it like this:

    >>> with SpecialFileOpener('C:\\test.txt', 'Hello world!') as f:
            print(f.read())
    
    Hello world!
    foo bar
    Everything is over.
    

    Using a context block with with is preferred for file objects (and other resources) anyway.

提交回复
热议问题