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?
CodePudding user response:
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?
CodePudding user response:
class Outer:
def __init__(self, df):
self.df = df
class Inner(Outer):
pass
Inner
will now inherit Outer
's properties and methods