Created
May 4, 2021 09:17
-
-
Save tinytengu/41709f097825c3edcd3be86d1bea8e02 to your computer and use it in GitHub Desktop.
Python Dictionary to an Object implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DictObject: | |
"""DictObject class""" | |
def __init__(self): | |
self._fields = {} | |
def add_field(self, name, value): | |
"""Add field to the DictObject fields list | |
:param name: field name | |
:type name: str | |
:param value: field value | |
:type value: any | |
""" | |
self._fields[name] = value | |
self.__setattr__(name, value) | |
def remove_field(self, name): | |
"""Remove field from the DictObject fields list | |
:param name: field name | |
:type name: str | |
""" | |
del(self._fields[name]) | |
self.__delattr__(name) | |
@classmethod | |
def load(cls, source): | |
"""Convert source tuple/list/dict to an DictObject object | |
:param source: data to convert | |
:type source: tuple/list/dict | |
:return: converted result | |
:rtype: DictObject or list of DictObject | |
""" | |
if isinstance(source, dict): | |
instance = cls() | |
for k, v in source.items(): | |
instance.add_field(k, cls.load(v)) | |
return instance | |
if not isinstance(source, (tuple, list)): | |
return source | |
return list(cls.load(value) for value in source) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment