0

I'm attempting to merge a few classes, based on variables, into a master class. Please see the code below and let me know if there's a more efficient, or proper, way on performing these actions. Thanks in advance

Concept: I have 1 main class that has a few methods. Then I have 2-5 sub classes that extend the main class. However, if I'm not using those methods then I don't inherit those methods nor properties, I only inherit based on what I need. The DriverFactory is then inherited by the class that uses it by the proper class className(DriverFactory) and the super(className, self).init(*args)

class DriverFactory(object):

    def __init__(self, *args):
        if "value1" in args:
            cls1 = classOne()
            self.inheritor(cls1)

        if "value2" in args:
            cls2 = classTwo()
            self.inheritor(cls2)

        if len(args) == 0:
            default = defaultCls()
            self.inheritor(default)

    def inheritor(self, obj):
        for i in obj.__dict__:
            self.__dict__[i] = obj.__dict__[i]
        methods = inspect.getmembers(obj, predicate=inspect.ismethod)
        for i in range(1, len(methods)):
            method_obj = methods[i]
            setattr(self, method_obj[0], method_obj[1])
jwalk
  • 1
  • 1
  • 1
    why not use interfaces? – Yu Zhang Jul 28 '16 at 03:35
  • Interfaces isn't a `thing` in Python and, rather, an abstract class can be used instead ===> http://stackoverflow.com/questions/372042/difference-between-abstract-class-and-interface-in-python – Carlos Jul 28 '16 at 04:19
  • Maybe a ```metaclass```? http://archive.oreilly.com/python/2003/04/17/metaclasses.html – wwii Jul 28 '16 at 04:33
  • So what do you want optimized? Selecting the classes? Use a dict `{'value1': classOne, ...}` for that if you have lots. Dynamically writing classes? Use `__new__` to write a proper class once, then reuse it, similar as [here](http://stackoverflow.com/a/38133854/5349916). – MisterMiyagi Jul 28 '16 at 05:05

0 Answers0