Search code examples
pythonclassoopobjectencapsulation

Creating classes with a lot of imported functions here and there


Let's say i have a lot of functions in alotoffunc.py that is used by more than 1 type of object.

Let's say ObjectI and ObjectII and ObjectXI all uses some functions in alotoffunc.py. And each of the Object were using different set of functions but all the objects have the variable object.table.

alotoffunc.py:

def abc(obj, x):
  return obj.table(x) * 2

def efg(obj, x):
  return obj.table(x) * obj.table(x)

def hij(obj, x, y):
  return obj.table(x) * obj.table(y)

def klm(obj, x, y):
  return obj.table(x) *2 - obj.table(y)

And then i import the functions and overload them:

import alotoffunc

class ObjectI:
  def abc(self, x):
    return alotoffunc.abc(self, x)

  def efg(self, x):
    return alotoffunc.efg(self, x)

class ObjectII:
  def efg(self, x):
    return alotoffunc.efg(self, x)
  def klm(self, x, y): 
    return alotoffunc.klm(self, x, y)

class ObjectXI:
  def abc(self, x):
    return alotoffunc.abc(self, x)
  def klm(self, x, y):
    return alotoffunc.klm(self, x, y)

It looks a like a big mess now, how should I go about building my object class and arrange my alotoffunc.py?


Solution

  • (1) You can have a base class that implements all the methods then override the unnecessary ones to raise a NotImplementedError in the subclasses.

    (2) You can have mixins to reduce repetition:

    import alotoffunc
    
    class MixinAbc:
        def abc(self, x):
            return alotoffunc.abc(self, x)
    
    class MixinEfg:
        def efg(self, x):
            return alotoffunc.efg(self, x)
    
    class MixinKlm:
        def klm(self, x, y):
            return alotoffunc.klm(self, x, y)
    
    class ObjectI(MixinAbc, MixinEfg):
        pass
    
    class ObjectII(MixinEfg, MixinKlm):
        pass    
    
    class ObjectXI(MixinAbc, MixinKlm):
        pass
    

    You can also combine this method with that of @cpburnz.