Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python打开一个文件并传递到类对象问题_Python - Fatal编程技术网

python打开一个文件并传递到类对象问题

python打开一个文件并传递到类对象问题,python,Python,我不是python专家,今天我只是想给出这样的代码: class MyFile(object): @classmethod def from_file_path(cls, file_path): with open(file_path, 'rb') as f: return cls(f, file_path) @classmethod def from_file_object(cls, file_object):

我不是python专家,今天我只是想给出这样的代码:

class MyFile(object):
    @classmethod
    def from_file_path(cls, file_path):
        with open(file_path, 'rb') as f:
            return cls(f, file_path)

    @classmethod
    def from_file_object(cls, file_object):
        return cls(file_descriptor=file_object)

    def __init__(self, file_descriptor, file_path=None):
        self._file_path = file_path
        self._fd = file_descriptor
        self._parse()

我的目的是让
with
自动调用
f.close()
,但是,我想知道这种用法是否会导致诸如内存泄漏之类的副作用或诸如崩溃之类的坏事情?

文件将在从
from\u File\u path
返回后关闭。您将返回在其
\u fd
属性中已关闭文件的对象。该属性似乎为真,因此尽管关闭了文件,但没有其他伤害?是的,没有其他伤害。