如何创建基于file.i的类

2024-10-06 07:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个模块,可以在几种不同的文件格式之间进行转换(例如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)

Tags: 文件实例方法io类型parameterparamvalue
3条回答

我现在找到了一个令人满意的方法来做我想做的事。下面是我的基类,它建立在file_io的基函数(但不是子类)上,是一个编写CSV文件的简单示例。我也有HTML、Verilog和其他格式的格式化程序。代码为:

class Formatter():
    ''' base class to manage the opening of a file in order to build classes which write a file
        with a specific format so as to be able to pass the formatting functions to a subroutine
        along with the file handle

        Designed to use with "with" statement and to shorten argument lists of functions which use
        the file
    '''

    def __init__(self, filename):
        ''' associate this instance with the given file handle
        '''
        self.f = open(filename, 'w')

    def wr(self, line, end='\n'):
        ''' write line given to file
        '''
        self.f.write(line + end)


    def wr_newline(self, num):
        ''' write num newlines to file
        '''
        self.f.write('\n'*num)


    def __enter__(self):
        ''' needed for use with with statement
        '''
        return self


    def __exit__(self, *args):
        ''' needed for use with with statement
        '''
        self.close()


    def close(self):
        ''' explicit file close for use with procedural progamming style
        '''
        self.f.close()



class CSV(Formatter):
    ''' class to write items using comma separated file format string formatting
        inherrits:
        => wr(line, end='\n'):
        => wr_newline(n):
        all file io functions via the self.f variable
    '''

    @staticmethod
    def pp(item):
        ''' 'pretty-print - can't have , or \n in strings used in CSV files
        '''
        return  str(item).replace('\n', '/').replace(',', '-')


    def __init__(self, filename):
        '''open filen given as a CSV file
        '''
        super().__init__(filename + '.csv')


    def wp(self, item):
        ''' write a single item to the file
        '''
        self.f.write(self.pp(item)+', ')


    def ws(self, itemlist):
        ''' write a csv list from a list variable
        '''
        self.wr(','.join([self.pp(item) for item in itemlist]))

我的两行解决方案如下:

with open(lib_loc + '\\' + lib_name + '.lib', 'w') as lib_file_handle:
    lib_file = Liberty(lib_file_handle)
    # do stuff using lib_file

类初始化如下:

def __init__(self, file):
    ''' associate this instance with the given file handle '''
    self.f = file

现在,我不再传递原始文件句柄,而是将类和函数一起传递给我的函数。你知道吗

最简单的功能是:

def wr(self, line):
    ''' write line given to file'''
    self.f.write(line + '\n')

这意味着我在复制文件.io班级。这就是我想避免的。你知道吗

这样想是不对的。你知道吗

你继承是为了被重用。基类提供了一个其他人可以使用的接口。对于类似文件的对象,它主要是readwrite。但是,您只想调用另一个函数simple_parameter。直接调用write可能会弄乱格式。你知道吗

你真的不希望它像文件一样。您想在用户调用simple_parameter时写入文件。实现应该委托给类似对象的成员文件,例如:

class LibFile:
    def __init__(self, file):
        self.file = file

    def simple_parameter(self, param, value):
        self.file.write('{}: {}\n'.format(param, value))

这很容易测试,因为您可以传入任何支持write的内容:

>>> import sys
>>> lib = LibFile(sys.stdout)
>>> lib.simple_parameter('name', 'Stephen')
name: Stephen

编辑:

如果确实希望类管理文件的生存期,可以提供close函数并使用^{}上下文管理器:

class Formatter:
    def __init__(self, filename, mode):
        self.file = open(filename, mode)

    def close(self):
        self.file.close()

用法:

class LibFormatter(Formatter):
    def simple_parameter(self, param, value):
        self.file.write('{}: {}\n'.format(param, value))

from contextlib import closing

with closing(LibFormatter('library.txt', 'w')) as lib:
    ... # etc

第二次编辑:

如果不想使用^{},可以编写自己的上下文管理器:

class ManagedFile:
    def __init__(self, filename, mode):
        self.file = open(filename, mode)

    def __enter__(self):
        return self

    def __exit__(self, *args):
        self.close()

    def close(self):
        self.file.close()

用法:

class LibFormatter(ManagedFile):
    def simple_parameter(self, param, value):
        self.file.write('{}: {}\n'.format(param, value))

with LibFormatter('library.txt', 'w') as lib:
    ... # etc

相关问题 更多 >