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

如何为动态创建的Python Enum类重载__str__方法?

Hey there! The issue you're running into is because you were modifying the metaclass's __str__ method instead of the dynamic enum class itself. Let's break down two solid solutions to get your custom string representation working with dynamically created enums.


Solution 1: Use a Custom Base Enum Class (Cleanest Approach)

The best way is to define a base Enum subclass with your desired __str__ method first, then use that base class to create your dynamic enum. This keeps things organized and avoids monkey-patching later.

from enum import Enum, auto

# Define a reusable base class with our custom string logic
class NameBasedStrEnum(Enum):
    def __str__(self):
        # Return the enum member's name instead of the default "<A.a_1: 1>"
        return self.name

# Create your dynamic enum using this base class
A = NameBasedStrEnum(
    'A',
    dict(('a_' + some_input, auto()) for some_input in ['1', '2', '3']),
    module=__name__
)

# Test it out!
print(A.a_1)  # Output: a_1
print(str(A.a_2))  # Output: a_2

This works because the dynamic enum inherits from NameBasedStrEnum, so all its members automatically use the overridden __str__ method.


Solution 2: Monkey-Patch the Dynamic Enum Class

If you can't predefine a base class (for whatever reason), you can directly override the __str__ method on the dynamically created enum class after it's made. Just make sure you're modifying the class itself, not its metaclass.

from enum import Enum, auto

# Create the dynamic enum normally first
A = Enum(
    'A',
    dict(('a_' + some_input, auto()) for some_input in ['1', '2', '3']),
    module=__name__
)

# Override __str__ directly on the A class
def custom_enum_str(self):
    return self.name

A.__str__ = custom_enum_str

# Or use a lambda for brevity (same result)
# A.__str__ = lambda self: self.name

# Test
print(A.a_3)  # Output: a_3
print(str(A.a_1))  # Output: a_1

Why Your Original Approach Failed

When you tried A.__class__.__str__ = lambda self: ..., you were modifying the metaclass (EnumMeta) that underpins all Enum classes. This would change the string representation for every Enum in your codebase, not just A. Instead, you need to target the __str__ method of the specific enum class (A) itself, which is a subclass of Enum.

Both solutions above correctly target the __str__ method of the dynamic enum class, so only members of A will use your custom string logic.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:33:49