python数据类型:枚举enum和json
Posted 风流 少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python数据类型:枚举enum和json相关的知识,希望对你有一定的参考价值。
一:枚举
from enum import Enum, unique
# 枚举中的key不能相同,value可以相同,如果希望value不相同可以使用@unique来限制
# IntEnum 表示value值只能是整型数字或者整型字符串
@unique
class Weekday(Enum):
monday = 1
tuesday = 2
wednesday = 3
thursday = 4
friday = 5
saturday = 6
sunday = 7
# 为枚举项添加其他属性,可以为同一个枚举项添加多个属性
Weekday.monday.label = '星期一'
Weekday.tuesday.label = '星期二'
Weekday.wednesday.label = '星期三'
Weekday.thursday.label = '星期四'
Weekday.friday.label = '星期五'
Weekday.saturday.label = '星期六'
Weekday.sunday.label = '星期日'
# 枚举可以使用==或者is关键字进行比较
monday = Weekday['monday']
monday2 = Weekday(1)
# <enum 'Weekday'> monday 1 星期一 True True
print(type(Weekday.monday),
Weekday.monday.name,
Weekday.monday.value,
Weekday.monday.label,
monday == monday2,
monday is monday2)
二:json
import json
# 对象转json字符串, json中有中文需要关闭ensure_ascii
user = "id": 1, "username": "admin", "name": "张无忌"
user_json = json.dumps(user, ensure_ascii=False)
# json字符串转对象
user_obj = json.loads(user_json)
以上是关于python数据类型:枚举enum和json的主要内容,如果未能解决你的问题,请参考以下文章