Python class with

Asked 6 days ago, Updated 6 days ago, 1 views

I made a Python code and called it with a statement.

There is no function that needs to be used separately even if it is used with, so I set it as follows. By the way, if you add the self.close() command to the exit function as follows, the following error message is exposed, did I enter the wrong command? Or is it not necessary to issue a self.close() command?

class a:
    def __init__(self):
            Rough command code

    def __enter__(self):
            return self

    def __exit__(self, exc_type, exc_value, traceback):
            Functions to run on shutdown

with a() as a:
object has no attribute 'close'

python class

2022-09-20 14:39

1 Answers

>>> f = open('')
>>> f
<_io.TextIOWrapper name='' mode='r' encoding='cp949'>

class TextIOWrapper(TextIOBase):

class TextIOBase(IOBase):

class IOBase(metaclass=abc.ABCMeta):
    def close(self):
    def __exit__(self, *args):

It's a class related to open()

_exit _ There is a function for self.close() so I think it works normally

f = open('something', flag)

with open('something',flag) as a:

The above two are the same.

The reason is that with is controlled by _enter_ and _exit_magic method, as in the initial question sentence.

Also, the contents returned to open() are designated with the correct wrapper class according to the flag at the end

Therefore, the close() function of the Wrapper Class is specified to clear the space that is malloc after the file is read (after the end of use) for that class. Close(): Note

of the above IOBase

In addition, when using with, the _exit_ method to finally release the used memory calls the close() function.

However, unlike IOBase class in question code statements, a class does not have a close() function defined.

I think you may have been confused because the class IOBase Class returned from the open() function is commonly used for use with.

2022-09-20 14:39

If you have any answers or tips

© 2022 pinfo. All rights reserved.