python打开一个文件并传递到类对象问题
我不是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):
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
属性中已关闭文件的对象。该属性似乎为真,因此尽管关闭了文件,但没有其他伤害?是的,没有其他伤害。