1

What I would like to do is access the inherited methods using a certain namespace, for example:

class ExtraMeths(object):
    def specialmeth():
        pass

class MainClass(ExtraMeths):
    def standardmeth():
       pass
myclass = MainClass()
myclass.standardmeth()  #works
myclass.specialmeth()  #also works, but not ideal

Now ideally what I would like to do is run myclass.ExtraMeths.specialmeth() where the name ExtraMeths is not important, but it is in its own 'property' of the main class. Also important that the inherited class is inherited, i.e. the same self variables are available to it.

The reason is that there are a lot of methods and I would like to bring some order to them, so grouping similar ones together seems to make sense.

RexFuzzle
  • 1,412
  • 2
  • 17
  • 30

1 Answers1

2

This should be done using composition:

class ExtraMeths(object):
    def __init__(self, main):
        self.main = main

    def specialmeth(self):
        # can use self.main here to access outer class variables

class MainClass(object):
    def __init__(self):
        self.extra_meths = ExtraMeths(self)

    def standardmeth(self):
        pass

myclass = MainClass()
myclass.standardmeth()
myclass.extra_meths.specialmeth()
Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
  • Very cool- thank you. Any way for it not to have to use self.main? – RexFuzzle Aug 31 '17 at 19:16
  • You don't need the `self.main` if `ExtraMeths` doesn't need to access anything on a `MainClass` instance to do it's work. – Josh Karpel Aug 31 '17 at 19:26
  • As stated in the question- it would be ideal if `ExtraMeths` acted like an inherited class of `MainClass`, i.e. shared the same self, but was access through the composition. – RexFuzzle Aug 31 '17 at 19:32
  • There is also a problem with garbage collection with this method as stated (and fixed) here: https://stackoverflow.com/a/10791613/2356861 – RexFuzzle Aug 31 '17 at 19:37
  • @RexFuzzle that should only be an issue f you plan on implementing a `__del__` method, which you probably shouldn't anyway... – juanpa.arrivillaga Aug 31 '17 at 19:39
  • @RexFuzzle you could use a [mixin](https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful), but that doesn't solve your namespacing issue. Unfortunately I think you're going to have to choose between solving one problem or the other. – Josh Karpel Aug 31 '17 at 19:41