python - 用于实例化类的模块级函数
问题描述
在同一个文件中使用模块级函数实例化一个类是一个好习惯吗?我使用 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 加载对象来读取和写入大量文件,所以我想以一种有组织、干净的方式来做这件事。我必须将属性设置为可选值,因为有时我还需要使用空对象。
解决方案
这正是类方法的用途:为您的对象提供替代构造函数。
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"))
推荐阅读
- java - 无法在 maven+cucumber 中运行测试
- html - 通过用撇号分隔的字符串中的反斜杠撇号替换撇号来修复 HTML
- python - 如何在 Python 或 C++ 中执行严格的整数优化?
- clojure - 为什么我在 Luminus (Clojure) 中看到参数不匹配错误?
- python - 如果行不包含熊猫中的模式,则使用 groupby 删除 groupbs
- javascript - 如何同步更新 mapbox gl 样式?
- swift - (SwiftUI) 将 Slider 和 TextField 绑定到同一个变量?
- laravel - Laravel + Nuxt - 如何在 VDS 中组合它们?
- cplex - 使用 PYOMO 在 CPLEX 日志上获取约束标签(非索引)
- python - 使用连续行作为 Y 轴的小提琴图