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

如何在Python中使用classmethod获取枚举类的指定值或值列表?

修正后的枚举类实现方案

你的代码问题在于get_that_string方法的参数定义和内部逻辑错误:参数只接受单个枚举实例,且错误地将传入的枚举项当作整个枚举类来遍历。以下是修正后的实现,支持传入单个或多个枚举项,返回对应的字符串列表:

from enum import Enum
from typing import List

class StrEnum(str, Enum):
    def __str__(self) -> str:
        return str.__str__(self)

class BunchOfCreatures(StrEnum):
    SPIDERS: str = "Spiders"
    BEETLES: str = "Beetles"
    HORSES: str = "Horses"

    @classmethod
    def get_that_string(cls, *args: "BunchOfCreatures") -> List[str]:
        return [item.value for item in args]

使用示例

  • 传入单个枚举项:
    print(BunchOfCreatures.get_that_string(BunchOfCreatures.HORSES))
    # 输出: ['Horses']
    
  • 传入多个枚举项:
    print(BunchOfCreatures.get_that_string(BunchOfCreatures.HORSES, BunchOfCreatures.BEETLES))
    # 输出: ['Horses', 'Beetles']
    

说明

  • 使用*args接收任意数量的BunchOfCreatures枚举实例,同时支持单个和多个输入场景
  • 遍历args中的每个枚举项,提取其value属性组成结果列表
  • 保留原StrEnum的__str__方法实现,不影响枚举项本身的字符串转换行为

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:05:23