python 中基于字符串的标志

问题描述 投票:0回答:1

对于我基于 python 的类,我想将输入字符串限制为某些字符串,因为它们代表我想要允许加载的文件结尾,即

class DemoClass:
    def __init__(self, allowed_endings: Literal[".csv", ".txt", ".docx"] = ".docx") -> None:
        self.allowed_endings: Literal[".csv", ".txt", ".docx"] = allowed_endings

现在,我想用基于标志的系统替换该实现,即

class DemoClass:
    def __init__(self, allowed_endings: AllowedFileEndings = AllowedFileEndings.TXT) -> None:
        self.allowed_endings: AllowedFileEndings = allowed_endings

这样我就可以写一个类似的类

class DemoClass:
    def __init__(self, allowed_endings: AllowedFileEndings = AllowedFileEndings.TXT | AllowedFileEndings.CSV) -> None:
        self.allowed_endings: AllowedFileEndings = allowed_endings

我知道 StrEnum,我可以在其中创建一个行为类似于枚举的类,但也可用于与字符串进行比较。不幸的是,它不适用于按位 OR/AND 运算符,如上所示。而且,它只适用于 python 3.11 及以上版本,而我仅限于 3.9.

有没有办法在 Python 3.9 中实现这样的 StrFlag 类?

理想情况下,我仍然可以使用基于字符串的理解,即

".csv" is in AllowedFileEndings.TXT | AllowedFileEndings.CSV

如果可能的话。

python string flags
1个回答
0
投票

您可以使用类的

|
__or__
方法为
__ror__
实现自定义行为。通过在 StrEnum 之上实现它们,你应该得到一个适合你需要的类。

from enum import StrEnum

class Extensions(StrEnum):
    TXT = ".txt"
    CSV = ".csv"
    DOCX = ".docx"
    DOC = ".doc"

    def __or__(self, other):
        if isinstance(other, set):
            return {self} | other
        elif isinstance(other, Extensions):
            return {self, other}
        else:
            raise TypeError
    def __ror__(self, other):
        if isinstance(other, set):
            return other | {self}
        elif isinstance(other, Extensions):
            return {other, self}
        else:
            raise TypeError
        
print(Extensions.TXT | Extensions.CSV | Extensions.DOCX)
© www.soinside.com 2019 - 2024. All rights reserved.