我正在编写一个模块,可以在几种不同的文件格式之间进行转换(例如vhdl到verilog、excel表到vhdl等)。这并不难,但是有很多特定于语言的格式化要做。我突然想到,一个优雅的方法是通过在每个文件格式类型上构建一个类来为每个文件格式类型创建一个类类型文件.io. 该类将继承文件的方法,但也能够读取或写入该文件的特定语法。我找不到任何文件io超类的例子以及如何编写它。我的想法是,要实例化它(打开文件),我可以使用:
my_lib_file = Libfile(filename, 'w')
为了给libfile写一个简单的参数,我可以使用
my_lib_file.simple_parameter(param, value)
这样一个类将以一种简洁的方式将我目前拥有的许多特定于文件的函数联系在一起。实际上,我更希望能够将类实例化为with语句的一部分,例如:
with Libfile(filename, 'w') as my_lib_file:
for param, value in my_stuff.items():
my_lib_file.simple_parameter(param, value)
我现在找到了一个令人满意的方法来做我想做的事。下面是我的基类,它建立在file_io的基函数(但不是子类)上,是一个编写CSV文件的简单示例。我也有HTML、Verilog和其他格式的格式化程序。代码为:
我的两行解决方案如下:
类初始化如下:
现在,我不再传递原始文件句柄,而是将类和函数一起传递给我的函数。你知道吗
最简单的功能是:
这意味着我在复制文件.io班级。这就是我想避免的。你知道吗
这样想是不对的。你知道吗
你继承是为了被重用。基类提供了一个其他人可以使用的接口。对于类似文件的对象,它主要是
read
和write
。但是,您只想调用另一个函数simple_parameter
。直接调用write
可能会弄乱格式。你知道吗你真的不希望它像文件一样。您想在用户调用
simple_parameter
时写入文件。实现应该委托给类似对象的成员文件,例如:这很容易测试,因为您可以传入任何支持
write
的内容:编辑:
如果确实希望类管理文件的生存期,可以提供close函数并使用^{} 上下文管理器:
用法:
第二次编辑:
如果不想使用^{} ,可以编写自己的上下文管理器:
用法:
相关问题 更多 >
编程相关推荐