Last active
June 28, 2023 19:56
-
-
Save jmemich/20244190e2ff398df87f to your computer and use it in GitHub Desktop.
Dynamic Inheritance Factory Class
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 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