Created
July 20, 2020 21:29
-
-
Save nschairer/2d3a846efe6f42da932d0a6f6fdb2915 to your computer and use it in GitHub Desktop.
Medium Python Dynamic Attributes
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
import json | |
#Unique type class to decipher between attributes | |
class ORMType: | |
def __init__(self, key, value): | |
self.key = key | |
self.value = value | |
def __repr__(self): | |
return str(self.value) | |
# Basic ORM class | |
class BasicORM: | |
def __init__(self, **kwargs): | |
for key, value in kwargs.items(): | |
setattr(self, key, ORMType(key, value)) | |
def toJson(self): | |
'''Helper method to dump ORM instance to json | |
''' | |
obj = {} | |
for attr in dir(self): | |
if isinstance(getattr(self, attr), ORMType): | |
obj[attr] = getattr(self, attr).value | |
return json.dumps(obj) | |
# Basic instance of ORM | |
textMessage = BasicORM( | |
date='12/31/2020', | |
uid='1234', | |
user='nschairer', | |
message='Simple text message' | |
) | |
###Display Text Message Information | |
print(textMessage.date) | |
print(textMessage.uid) | |
print(textMessage.toJson()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment