Let's say that I have a class like this
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
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
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
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:
member.__class__.__name__
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.