Reputation: 1848
Say all subclass can get its own choice like class.choice()
from enum import IntEnum
class CompanyType(IntEnum):
BySelf = 1
Agency = 2
@staticmethod
def choice():
return [
(i.value, i.name) for i in CompanyType
]
class CompanyStatus(IntEnum):
StartUp = 1
LargeCompany = 2
@staticmethod
def choice():
return [
(i.value, i.name) for i in CompanyStatus
]
...
How can I abstract a base class that can be inherited with method choice
Expected as:
from enum import IntEnum
class ChoiceBase_():
@staticmethod
def choice():
return [
(i.value, i.name) for i in specified_subclass
]
class CompanyType(ChoiceBase_, IntEnum):
BySelf = 1
Agency = 2
class CompanyStatus(ChoiceBase_, IntEnum):
StartUp = 1
LargeCompany = 2
print(CompanyType.choice())
print(CompanyStatus.choice())
Upvotes: 0
Views: 48
Reputation: 18106
Use the classmethod
decorator in order to get the classes constants:
class ChoiceBase_():
@classmethod
def choice(cls):
return [(i.value, i.name) for i in cls]
class CompanyType(ChoiceBase_, IntEnum):
BySelf = 1
Agency = 2
class CompanyStatus(ChoiceBase_, IntEnum):
StartUp = 1
LargeCompany = 2
print(CompanyType.choice())
print(CompanyStatus.choice())
Out:
[(1, 'BySelf'), (2, 'Agency')]
[(1, 'StartUp'), (2, 'LargeCompany')]
Edit:
In Python36, inheriting from int
makes sure to use use int.__new__()
as stated in the error message:
from enum import Enum
class CompanyStatus(int, ChoiceBase_, Enum):
StartUp = 1
LargeCompany = 2
Upvotes: 4