简体   繁体   中英

Accessing class file from multiple methods in Python

My question relates mostly to how you use the with keyword in a class in Python.

If you have a Class which contains a file object, how do you use the with statement, if at all.

For example, I don't use with here:

class CSVLogger:
    def __init__(self, rec_queue, filename):
        self.rec_queue = rec_queue
        ## Filename specifications
        self.__file_string__ = filename
        f = open(self.__file_string__, 'wb')
        self.csv_writer = csv.writer(f,  newline='', lineterminator='\n', dialect='excel')

If I then do things to the file in another method, For example:

    def write_something(self, msg):
        self.csv_writer(msg)

Is this suitable? Should I include the with somewhere? I'm just afraid that one the __init__ exits, the with exits and might close the file?

Yes, you are correct with automatically closes the file when its scope ends, so if you use with statement in your __init__() function, the write_something function would not work.

Maybe you can use the with statement in the main part of the program, and instead of opening the file in __init__() function you can pass in the file object as a parameter to the __init__() function. and then do all operations you would like to do in the file within the with block.

Example -

Class would look like -

class CSVLogger:
    def __init__(self, rec_queue, filename, f):
        self.rec_queue = rec_queue
        ## Filename specifications
        self.__file_string__ = filename
        self.csv_writer = csv.writer(f,  newline='', lineterminator='\n', dialect='excel')
    def write_something(self, msg):
        self.csv_writer(msg)

The main program may look like -

with open('filename','wb') as f:
    cinstance = CSVLogger(...,f) #file and other parameters
    .... #other logic
    cinstance.write_something("some message")
    ..... #other logic

Though if this complicates thing a-lot, you are better off not using the with statement and rather making sure that you close the file when when its need is over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM