Python 类 "Main"值

标签 python

我对 Python 还很陌生,一直在编写从二进制文件读取和写入的代码。

我决定为文件中包含的每种类型的数据创建类,并为了保持它们的组织性,我创建了一个它们都会继承的类,称为 InteriorIO。我希望每个类都有一个读写方法,可以从文件中读取数据或将数据写入文件。然而,在继承 InteriorIO 的同时,我希望它们的行为像 str 或 int 一样,因为它们返回它们包含的值,所以我会修改 __str____int__取决于它们最相似的部分。

class InteriorIO(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def read(this, f):
        pass

    @abstractmethod
    def write(this, f):
        pass

class byteIO(InteriorIO):
    def __init__(this, value=None):
        this.value = value

    def read(this, f):
        this.value = struct.unpack("B", f.read(1))[0]

    def __str__:
        return value;

class U16IO(InteriorIO):
    def __init__(this, value=None):
        this.value = value

    def read(this, f):
        this.value = struct.unpack("<H", f.read(2))[0]

    def __int__:
        return value;

# how I'd like it to work
f.open("C:/some/path/file.bin")
# In the file, the fileVersion is a U16
fileVersion = U16IO()
# We read the value from the file, storing it in fileVersion
fileVersion.read(f)
# writes the fileVersion that was just read from the file
print(str(fileVersion))
# now let's say we want to write the number 35 to the file in the form of a U16, so we store the value 35 in valueToWrite
valueToWrite = U16IO(35)
# prints the value 35
print(valueToWrite)
# writes the number 35 to the file
valueToWrite.write(f)
f.close()

底部的代码可以工作,但是类感觉错误并且太模糊。我正在设置 this.value,这是我想出的一个随机名称,为每个对象设置为一种“主”值,然后将所述值返回为我想要的类型.

组织我的类的最干净的方法是什么,使它们都继承自 InteriorIO,但它们的行为就像 str 或 int 一样返回它们的值?

最佳答案

我认为在这种情况下您可能需要考虑Factory Design Pattern .

这是一个简单的例子来解释这个想法:

class Cup:
    color = ""

    # This is the factory method
    @staticmethod
    def getCup(cupColor, value):
        if (cupColor == "red"):
            return RedCup(value)
        elif (cupColor == "blue"):
            return BlueCup(value)
        else:
            return None

class RedCup(Cup):
    color = "Red"

    def __init__(self, value):
        self.value = value


class BlueCup(Cup):
    color = "Blue"

    def __init__(self, value):
        self.value = value

# A little testing
redCup = Cup.getCup("red", 10)
print("{} ({})".format(redCup.color, redCup.__class__.__name__))

blueCup = Cup.getCup("blue", 20)
print("{} ({})".format(blueCup.color, blueCup.__class__.__name__))

所以你有一个工厂Cup,它包含一个静态方法getCup,它给定一个值,将决定“生成”哪个对象,因此标题为“工厂”。

然后在您的代码中,您只需调用工厂的 getCup 方法,这将返回您可以使用的适当类。

他们处理 __int____str__ 的方法我认为在您缺少的类中,只需实现它并返回 None 即可。因此,您的 U16IO 应该实现一个返回 None__str__ 方法,并且您的 byteIO 应该实现一个也返回 None__int__ 方法。 .

关于Python 类 "Main"值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40827148/

相关文章:

python - 如何使用 python bs4 抓取包含分页下一个标签的股票数据?

python - 如何从 model_utils 三重选择中获取 key ?

python - 感兴趣区域时无类型错误

python - 如何在django中保存多对多关系

python - 在 Google Cloud Compute Engine 上运行 python 脚本

python - Cython 生成的 C++ 代码中可能存在错误

python - PyYAML 用下划线替换键中的破折号

python - 如何在 ansible.cfg 文件中添加多个库路径

python - 如何使用字典中的键查找值

PYTHON:使用 python 变量更新多列