Skip to content

Instantly share code, notes, and snippets.

@nschairer
Created July 20, 2020 21:29
Show Gist options
  • Save nschairer/2d3a846efe6f42da932d0a6f6fdb2915 to your computer and use it in GitHub Desktop.
Save nschairer/2d3a846efe6f42da932d0a6f6fdb2915 to your computer and use it in GitHub Desktop.
Medium Python Dynamic Attributes
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