Python – Dynamically created Ennum’s method overload

Dynamically created Ennum’s method overload… here is a solution to the problem.

Dynamically created Ennum’s method overload

The goal is to overload Enum's __str__(self) method with dynamically created properties.

Dynamic enumerations can be created with

the following

[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 can be used

[2]:

class A(Enum):
    a_no_input = auto()

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

Separately, both examples work as needed. Combine the two I’ve tried:

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

But this does not change 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)

However, this does not create static properties that are accessible through the A.a_1.

How do I dynamically create static properties of an enumeration and overload the methods of the parent class (super class) Enum?

Solution

Your third code snippet should be:

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

Notice that I took the __class__ out.

Related Problems and Solutions