我是Python初学者,我想用一个方法列出所有枚举项。该方法在基类中定义为类函数。 基类有子类。并且子类还有额外的子类。 我使用了 python 扩展可扩展枚举。
致以诚挚的问候
马丁
from enum import Enum
from extendableenum import inheritable_enum
@inheritable_enum
class baseClassHours(Enum):
NOHOUR= 'NoHour'
@classmethod
def list(cls):
return list(map(lambda c: c.name, eval(cls.__name__)))
@classmethod
def listValue(cls):
return list(map(lambda c: c.value, eval(cls.__name__)))
class night(baseClassHours):
ONE = '1'
TWO = '2'
THREE = '3'
FOUR = '4'
FIVE = '5'
SIX = '6'
class morning(baseClassHours):
SEVEN = '7'
EIGHT = '8'
NINE = '9'
TEN = '10'
ELEVEN = '11'
TWELVE = '12'
class afternoon(baseClassHours):
THIRTEEN = '13'
FOURTEEN = '14'
FIFTEEN = '15'
SIXTEEN = '16'
SEVENTEEN = '17'
EIGHTEEN = '18'
class evening(baseClassHours):
NINETEEN = '19'
TWENTY = '20'
TWENTYONE = '21'
TEWNTYTWO = '22'
TWENTYTHREE = '23'
TWENTYFOUR = '24'
print(evening.list())
print(evening.NOHOUR.value)
print(evening.NINETEEN.value)
print(evening.TWENTY.value)
print(evening.TWENTYONE.value)
print(evening.TWENTYTWO.value)
print(evening.TWENTYTHREE.value)
print(evening.TWENTYFOUR.value)
预期输出:
['NOHOUR', 'NINETEEN', 'TWENTY', 'TWENTYONE', 'TEWNTYTWO', 'TWENTYTHREE', 'TWENTYFOUR']
NoHour
19
20
21
22
23
24
但我明白:
['NINETEEN', 'TWENTY', 'TWENTYONE', 'TEWNTYTWO', 'TWENTYTHREE', 'TWENTYFOUR']
NoHour
19
20
21
22
23
24
根据项目存储库中提供的示例,看起来无法以这种方式访问
https://github.com/gweesip/extendable-enum/blob/main/docs/examples/example_inheritable_enum.py
# And create a subclass with new members
class MoreFruit(Fruit):
MANGO = 4
DRAGONFRUIT = 5
# Only the non-inherited members will be in _member_names_
print(MoreFruit._member_names_)
# Inherited members are not included in dir, len, reversed or iteration
print(dir(MoreFruit))
print(len(MoreFruit))
print([member for member in reversed(MoreFruit)])
print([member for member in MoreFruit])
# Inherited members can not be accessed by name
try:
MoreFruit['APPLE']
except KeyError:
print('Access to super members by name not supported')
# or by value
try:
MoreFruit(1)
except ValueError:
print('Access by value not allowed')
# but can still be accessed as attributes.
print(MoreFruit.APPLE)
# The returned members are the superclass members.
print(MoreFruit.APPLE is Fruit.APPLE)