You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.9如何实现支持位运算的字符串标志类(StrFlag)

在Python 3.9中实现支持位运算与字符串判断的文件后缀标志类

Python 3.9没有内置的StrFlag类型,但可以基于enum.Flag(Python 3.6及以上支持)扩展,实现支持位运算、字符串后缀判断的枚举类,完全适配你的需求。

实现代码

from enum import Flag, auto
from typing import Set

class AllowedFileEndings(Flag):
    # 定义枚举成员,auto()自动分配2的幂次值,保证位运算有效性
    CSV = auto()
    TXT = auto()
    DOCX = auto()

    # 映射枚举成员到对应的文件后缀
    _suffix_map = {
        CSV: ".csv",
        TXT: ".txt",
        DOCX: ".docx"
    }

    @property
    def suffixes(self) -> Set[str]:
        """获取当前标志组合对应的所有文件后缀集合"""
        return {self._suffix_map[member] for member in AllowedFileEndings if member in self}

    def __contains__(self, item: str) -> bool:
        """支持直接判断字符串后缀是否在当前标志组合中"""
        return item in self.suffixes

使用示例

定义DemoClass类

class DemoClass:
    # 支持单个标志或组合标志作为默认值
    def __init__(self, allowed_endings: AllowedFileEndings = AllowedFileEndings.TXT | AllowedFileEndings.CSV) -> None:
        self.allowed_endings: AllowedFileEndings = allowed_endings

验证功能

# 单个标志实例测试
demo_single = DemoClass(AllowedFileEndings.DOCX)
print(".docx" in demo_single.allowed_endings)  # 输出: True
print(".txt" in demo_single.allowed_endings)   # 输出: False

# 组合标志实例测试
demo_combined = DemoClass(AllowedFileEndings.TXT | AllowedFileEndings.CSV)
print(".csv" in demo_combined.allowed_endings) # 输出: True
print(".docx" in demo_combined.allowed_endings)# 输出: False

核心实现说明

  • 位运算支持:enum.Flag会自动为每个auto()成员分配2的幂次数值,确保|(位或)、&(位与)等操作能正确组合/筛选标志。
  • 字符串判断:通过重写__contains__方法,直接将字符串后缀的判断映射到内部维护的后缀集合中。
  • 后缀映射:用_suffix_map统一管理枚举成员与后缀的对应关系,避免代码硬编码,便于后续维护。

内容的提问来源于stack exchange,提问作者arc_lupus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:30:18