MLmuchAmaze
MLmuchAmaze

Reputation: 499

Method overloading of dynamically created Enum

The goal is to overload the __str__(self) method of an Enum with dynamically created attributes.

A dynamic enum may be created with

[1]:

from enum import Enum, auto

A = Enum('A',
         dict(('a_'+some_input, auto())
              for some_input in ['1','2','3']),
         module=__name__)

Method overloading may be done with

[2]:

class A(Enum):
    a_no_input = auto()

    def __str__(self):
        return str(self.name)

Separatly, both examples work as needed. To combine both I tried:

[1]: ...
A.__class__.__str__ = lambda self: str(self.name)

But this doesn't alter the output of print(A.a_1).

and

class A(Enum):
    def __init__(self):
        super('A',
              dict(('a_' + some_input, auto())
                   for some_input in ['1', '2', '3']),
              module=__name__)

    def __str__(self):
        return str(self.name)

But this doesn't create static attributes that can be accessed via A.a_1.

How do I dynamically create static attributes of an enum and overload the methods of the super class Enum?

Upvotes: 3

Views: 145

Answers (2)

VPfB
VPfB

Reputation: 17282

Another alternative is [2] + [1]. Enumerations can be subclassed if they are empty:

from enum import Enum, auto

class EnumStr(Enum):
    def __str__(self):
        return str(self.name)

A = EnumStr('A',
         dict(('a_'+some_input, auto())
              for some_input in ['1','2','3']),
         module=__name__)

print(A.a_1)

Upvotes: 1

Ethan Furman
Ethan Furman

Reputation: 69051

Your third code snippet should be:

A.__str__ = lambda self: str(self.name)

Notice I took __class__ out.

Upvotes: 2

Related Questions