首页 > 解决方案 > 用于实例化类的模块级函数

问题描述

在同一个文件中使用模块级函数实例化一个类是一个好习惯吗?我使用 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")

另一种选择可能是创建一个类方法来做同样的事情。

#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 加载对象来读取和写入大量文件,所以我想以一种有组织、干净的方式来做这件事。我必须将属性设置为可选值,因为有时我还需要使用空对象。

标签: pythonpython-2.7class-method

解决方案


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

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 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"))

推荐阅读