Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call the constructor of a class that inherits Enum without arguments?

I have multiple classes, some inherit Enum, others don't and all of them end up mixed in big arrays such as show below:

from enum import Enum

class TestEnum(Enum):
    VAL_A = 0
    VAL_B = 1

class TestNotEnum():
    def __init__(self):
        self.var = 1

As I wish to have a code as simple as possible for others to use, I would like to call the constructors of all the classes the same way to avoid as much confusion as possible.

This is how I would like to initialize them :

classes = [TestEnum(), TestNotEnum()]

The TestNotEnum class has no issues with it but the TestEnum throws the following exception : TypeError: __call__() missing 1 required positional argument: 'value'. This is due to my (bad) use of Enum.

What can I do in order to have the TestEnum class still inherit Enum and yet have a constructor that has no arguments ?

I tried the following ( and a few similar tweaks ):

class TestEnum(Enum):
    VAL_A = 0
    VAL_B = 1
    def __init__(self):
        super(TestEnum, self).__init__()

but I only end up with different errors such as TypeError: __init__() takes 1 positional argument but 2 were given

like image 804
Matthieu Raynaud de Fitte Avatar asked Oct 29 '25 17:10

Matthieu Raynaud de Fitte


1 Answers

One option you have is to make factory functions named like your enums:

from enum import Enum

class TestEnum(Enum):
    VAL_A = 0
    VAL_B = 1

def TestEnum1():
    return TestEnum

class TestNotEnum():
    def __init__(self):
        self.var = 1


instances = [TestEnum1(), TestNotEnum()]
print(instances)

Output:

[<enum 'TestEnum'>, <__main__.TestNotEnum object at 0x03648E30>]
like image 69
quamrana Avatar answered Oct 31 '25 06:10

quamrana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!