代码之家  ›  专栏  ›  技术社区  ›  cap

用于实例化类的模块级函数

  •  0
  • cap  · 技术社区  · 8 年前

    在同一个文件中使用模块级函数实例化类是一个好的实践吗?我使用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加载对象来读写大量文件,所以我希望以一种有组织的、干净的方式来完成这项工作。我必须将属性设置为可选值,因为有时我还需要使用空对象。

    1 回复  |  直到 8 年前
        1
  •  0
  •   chepner    8 年前

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

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