-1

If I have the below class, is there a way to pass a variable that was defined in the outer class __init__ constructor into the inner class constructor in the inner class?

class Outer:

     def __init__(self, df):
        self.df = df

     class Inner:
          ## Looking to pass the df into this class

I stumbled across this solution but I wanted to know if there was a simpler solution?

I also came across this solution but with this, I'd have to insert the df when calling the inner class. Is there a way to avoid this whereby if its initialised in the outer class, I can automatically retrieve it when I call the inner class or is this unavoidable?

Kale
  • 67
  • 5
  • Why are you trying to do this? How are you designing your program? – Be Chiller Too Oct 20 '21 at 12:22
  • 1
    There's no inherent connection between "nested classes". You may as well write them not nested, side by side, for the same effect. So no, there's no inherent way. – deceze Oct 20 '21 at 12:23
  • @BeChillerToo Trying to make a class of custom stock indicators to then store on github as a private module and then import into python. I wanted to avoid initialising of every other class in the `__init__.py` file and instead call the one outer class to have access to the others. There are quite a few. – Kale Oct 20 '21 at 12:31
  • @deceze Alright, thanks for this. – Kale Oct 20 '21 at 12:31

2 Answers2

1

You don't have an inner object until you create one, at which point you can pass any attributes of the outer class:

class Outer:
     def __init__(self, df):
        self.df = df
        self._inner = self.Inner(self.df)

     class Inner:
         def __init__(self, parent_df):
            self.parent_df = parent_df 

Also see Is it good practice to nest classes?

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • Alright, so pretty much like the second link in my original post. Guess it cannot be avoided then. Thanks! – Kale Oct 20 '21 at 12:37
-1
class Outer:

    def __init__(self, df):
        self.df = df

    class Inner(Outer):
        pass

Inner will now inherit Outer's properties and methods

rosbif
  • 11
  • 4
  • 1
    With this indentation you'll get `NameError: name 'Outer' is not defined` – Matthias Oct 20 '21 at 12:28
  • Thanks for your response. This was what I was avoiding as indicated in my comment to @BeChillerToo's comment. But if there is no inherent way of doing this, I'd have to rely on it. Thanks! – Kale Oct 20 '21 at 12:32
  • @JackGoodall Following your indentation edit, this brings up an error `'Outer' is not defined` as @Matthias was saying in his comment. It works when treated as separated classes rather than nested classes. Either way thanks! – Kale Oct 20 '21 at 12:40