[英]Getting the name of python enum class
Let's say that I have a class like this假设我有一个像这样的 class
class ErrorCreatingObjectResult(enum.Enum):
NONE = 0
OBJECT_ALREADY_EXIST = 1
UID_NOT_REGESTIRE = 2
CREATOR_NOT_REGESTIRE = 3
and an object with an attribute from this class和一个 object 具有来自此 class 的属性
class CreatingObjectMessage:
def __init__(self) -> None:
self.message = 'done creating object'
self.error = False
self.errorType = ErrorCreatingObjectResult.NONE
and I want to generate the dict object from this class by calling我想通过调用从这个 class 生成字典 object
def convert2serialize(obj):
if isinstance(obj, dict):
return {k: convert2serialize(v) for k, v in obj.items()}
elif hasattr(obj, "_ast"):
return convert2serialize(obj._ast())
elif not isinstance(obj, str) and hasattr(obj, "__iter__"):
return [convert2serialize(v) for v in obj]
elif hasattr(obj, "__dict__"):
return {
k: convert2serialize(v)
for k, v in obj.__dict__.items()
if not callable(v) and not k.startswith('_')
}
else:
return obj
r = CreatingObjectMessage()
convert2serialize(r)
this giving me an empty results这给了我一个空的结果
Editing the convert2serialize function fixed it编辑 convert2serialize function 修复它
def convert2serialize(obj):
if isinstance(obj, enum.Enum):
return {type(obj).mro()[0].__name__: obj.name}
if isinstance(obj, dict):
return {k: convert2serialize(v) for k, v in obj.items()}
elif hasattr(obj, "_ast"):
return convert2serialize(obj._ast())
elif not isinstance(obj, str) and hasattr(obj, "__iter__"):
return [convert2serialize(v) for v in obj]
elif hasattr(obj, "__dict__"):
return {
k: convert2serialize(v)
for k, v in obj.__dict__.items()
if not callable(v) and not k.startswith('_')
}
else:
return obj
Getting the name of an enum member's class is as easy as:获取枚举成员的 class 的名称非常简单:
member.__class__.__name__
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.