开发者

A custom file class. Is this feasible?

Currently I'm reading and writing binary files and am calling the struct pack/unpack functions frequently. Rather than constantly having to write something like

struct.unpack("3f", myFile.read(12))

I decided to write a function to save myself some typing, so the equivalent of the above statement in my code is

my_unpack(myFile, '3f')

Where my_unpack is defined as

struct.unpack(fmt, f.read(struct.calcsize(fmt))

But then I'm thinking what if I instead wrote things like

myFile.get_float(3)
myFile.get_char(12)
myFile.get_string(20)

It would make i开发者_开发问答t a little easier to read I believe, especially since the syntax for packing and unpacking might look daunting for those that are not familiar with it.

Would this be enough reason to write my own class that inherits the File class just to provide a couple extra methods?


Don't subclass. Instead, compose:

class StructReader(object):
    def __init__(self, input_file):
        self.input_file = input_file

    def get_float(self, n):
        fmt = ...
        return struct.unpack(fmt, self.input_file.read(struct.calcsize(fmt)))

    ...

When you subclass, you have to worry about namespace collisions. Composition avoids this problem.


The concept you are detailing is called a Wrapper, it implements the Facade design pattern. The reason for the existence of wrappers is to make calling methods on the parent class easier - exactly what you want to do. I don't see a problem with it.


In general - yes, why not?

But why would you want to inherit from File? Why not use composition / break dependencies?

class BinaryReader(object):
    def __init__(self, source):
        self.source = source

    def read_char(l):
        fmt = str(l) + 'c'
        data = self.source.read(struct.calcsize(fmt))
        return struct.unpack(fmt, data)
    ....
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜