0

SITUATION: Two classes that, at high level, has the same attributes (almost) and methods (almost). One class executes its methods in a local machine whereas the other in a remote one.

OBJECTIVE: Implement a third class that wrappers both classes and handles all necessary stuff in a way, that for the user, it will like as there is only the third class.

PATTERN THOUGHT:

class _Run_Local:
   def __init__(self,a,b,c):
       pass
   def apple(self):
       pass
   def orange(self):
       pass

class _Run_Cluster:
    def __init__(self,a,b,c,d):
       pass
    def apple(self):
       pass
    def orange(self):
       pass
    def banana(self):
       pass

class Run:
   def __init__(self,machine,a,b,c,d=''):
      if machine == 'local':
         self.obj = _Run_Local(a,b,c)
      if machine = 'cluster':
         self.obj = _Run_Cluster(a,b,c,d)

USAGE EXAMPLE:

run1 = Run('local,'a,b,c)
run1.apple()
run1.orange()
run2 = Run('cluster',a,b,c,d):
run2.apple()
run2.orange()
run2.banana()

I though in use inheritance. But, since the two classes have not exactly the same methods and attributes it seems to me that will not work fine. Then I saw some class wrapper implementation as this one. But, again, I not sure if it will handle all attributes and methods issues. So, here is the question: What should be a good class design approach to handle with this situation?

Randerson
  • 775
  • 1
  • 5
  • 19
  • Read about the [factory design pattern](https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html). This is exactly the scenario to use that – Tomerikoo Aug 12 '19 at 12:35

1 Answers1

0

Thanks Tomerikoo. After read the suggested reference I can with this solution.

class IMEX:
    def __new__(cls,type, a, b, c, d=''):
        if type == 'local': return _IMEX_Local(a,b,c)
        if type == 'cluster': return _IMEX_Cluster(a,b,c,d)
        assert 0, 'Bad creation {}'.format(type)

class _IMEX_Local:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def hello(self):
        print('I am _IMEX_Local')

    def hello_local(self):
        print('Hello')

class _IMEX_Cluster:
    def __init__(self, a, b, c, d):
        self.a = a
        self.b = b
        self.c = c
        self.d = d

    def hello(self):
        print('I am _IMEX_Cluster')

    def hello_cluster(self):
        print('Hello')

if __name__ == '__main__':
    imex1 = IMEX('local', 1, 2, 3)
    imex1.hello()
    imex2 = IMEX('cluster', 1, 2, 3,4)
    imex2.hello()

It attends to my expectation!!! :)

Randerson
  • 775
  • 1
  • 5
  • 19