Skip to content

Instantly share code, notes, and snippets.

@jmemich
Last active June 28, 2023 19:56
Show Gist options
  • Save jmemich/20244190e2ff398df87f to your computer and use it in GitHub Desktop.
Save jmemich/20244190e2ff398df87f to your computer and use it in GitHub Desktop.
Dynamic Inheritance Factory Class
class Database(object):
def _print(self):
print('Database class')
class Local(object):
def _print(self):
print('Local class')
class BaseThing(object):
def __init__(self):
self.is_base = True
def _print(self):
raise NotImplementedError
class ThingFactory(object):
"""
create Thing() objects which inherit from either 'Local' or 'Database'
classes depending on the arguments provided
"""
@staticmethod
def make_thing(_type):
hack = BaseThing() # how to fix this ?
return type('BaseThing', (eval(_type), ), hack.__dict__)
# define a dynamically inherited Sample() class that also inherits from Local()
Thing = ThingFactory.make_thing('Database')
# create instance of this class
loc_thing_instance = Thing()
# check that instance is correct!
loc_thing_instance._print() # prints correctly
print(loc_thing_instance.is_base) # is_base = True!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment