使用枚举类属性的正确方法
很少有.xlsx文件存储我指的数据。 将它们添加到枚举课程中。在源代码文件中,我需要在此处获取此枚举类的成员的一些属性,例如此处的文件名。 以下代码是否可以很好地解决问题,还是有根据最佳实践对其进行重新处理的途径?谢谢你!
from enum import Enum
class Data(Enum):
TYPE_A = 1
TYPE_B = 2
TYPE_C = 3
TYPE_D = 4
TYPE_E = 5
TYPE_F = 6
TYPE_G = 7
@property
def file_name(cls):
FILE_NAMES_DATA = (
'TYPE_A.xlsx',
'TYPE_B.xlsx',
'TYPE_C.xlsx',
'TYPE_D.xlsx',
'TYPE_E.xlsx',
'TYPE_F.xlsx',
'TYPE_G.xlsx',
)
MAP_DATA = {
member: file_name for member, file_name in zip(Data, FILE_NAMES_DATA)
}
return MAP_DATA[cls]
Has few .xlsx files storing the data I refer to.
Added them up to Enum Class. Within the source code file I need to obtain some properties of the members of this Enum class, like file name here.
Would the below code serve the problem well or there is an avenue to rework it in accordance with the best practices? Thank you!
from enum import Enum
class Data(Enum):
TYPE_A = 1
TYPE_B = 2
TYPE_C = 3
TYPE_D = 4
TYPE_E = 5
TYPE_F = 6
TYPE_G = 7
@property
def file_name(cls):
FILE_NAMES_DATA = (
'TYPE_A.xlsx',
'TYPE_B.xlsx',
'TYPE_C.xlsx',
'TYPE_D.xlsx',
'TYPE_E.xlsx',
'TYPE_F.xlsx',
'TYPE_G.xlsx',
)
MAP_DATA = {
member: file_name for member, file_name in zip(Data, FILE_NAMES_DATA)
}
return MAP_DATA[cls]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
值
1
-7
毫无意义吗?文件名与成员名称相同吗? ('type_a'
,'type_b'
等)在这种情况下,您可以做:Are the values
1
-7
meaningless? Are the file names the same as the member names? ('TYPE_A'
,'TYPE_B'
, etc.) In that case you can do:您可以通过定义枚举
@property
在file_names_data
中手动创建文件名。Instead of creating file names manually in
FILE_NAMES_DATA
, You can create them dynamically by defining a enum@property
.