要实例化的模块级函数 类

Module-level functions to instantiate classes

在同一文件中使用模块级函数实例化 class 是一种好习惯吗?我使用 YAML 创建对象的实例。

这是我的意思的一个例子。

#file.py
def newfile(path):
    with open(path) as f:
        return File(f.read())

class File(object):

    def __init__(self,content=None):
        self.content = content  

#main.py
import newfile
file = newfile("/path/to/file.txt")

另一种选择是创建一个 class 方法来执行相同的操作。

#file.py
class File(object):

    def __init__(self,content=None):
        self.content = content  

    @classmethod
    def new(cls,path):
        with open(path) as f:
             return cls(f.read())

#main.py
import File
file = File.new("/path/to/file.txt")

我需要做这样的事情的原因是我从 YAML 加载对象来读写大量文件,所以我想以一种有组织、干净的方式来做这件事。我必须将属性设置为可选值,因为有时我还需要使用空对象。

这正是 class 方法的用途:为您的对象提供备用构造函数。

class File(object):
    def __init__(self, content=None):
        self.content = content

    @classmethod
    def from_file(cls, path):
        with open(path) as f:
            return cls(f.read())

但是,一种可能更简洁的方法是 __init__ 既没有文件路径也没有原始数据,而是一个类似文件的对象。然后,您的 class 只需要支持一个用例,即从类似文件的对象中读取。

class File(object):
    def __init__(self, f):
        self.content = f.read()

现在,您的呼叫者负责打开文件:

with open(path) as fh:
    f = File(fh)

或创建其他一些类似文件的对象:

import StringIO

f = File(StringIO.StringIO("some data here"))