Sunday 12 September 2021

Python: Add methods to the enum

You can add class method, static method, special methods and normal method to the enum. Let’s see it with an example.

 

addMethodsToEnum.py

from enum import Enum

class Test(Enum):        
    A = 1
    B = 1
    C = 23

    def describe(self):
        return self.name, self.value
    
    def __str__(self):
        return 'I am {0} and has value {1}'.format(self.name, self.value)

    @classmethod
    def decribeEnum(cls):
        return "I am Test enum"

print(Test.decribeEnum())
print(Test.C.describe())
print(str(Test.C))

Output

I am Test enum
('C', 23)
I am C and has value 23


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment