Getting variables from an outer class

I’m doing a project in Python which requires me to make a nested class. I need to get a variable from the class it is nested in but haven’t been able to. I want to be able to get the self variables from Parent in the Child class but my code isn’t working, is there any way I could inherit the Parent class’ variables? Here is what I tried:

class Parent:
  def __init__(self):
    self.x = 1;
    self.y = 2;
  class Child:
    def __init__(self):

    def parent_vars(self):
      att = super()["x"];

parent = Parent();
child = parent.Child();



In python, unlike in Java, a class serves more as a namespace than as an object. An inner class (in this case Parent.Child) is no different semantically than the same class defined as a standalone – the outer class is simply how it’s accessed (and it’s accessed statically, not requiring an instance – again unlike Java).

If you want a Child to take its Parent‘s variables, you’ll need to tell the Child explicitly which object is its Parent:

class Parent:
  def __init__(self):
    self.x = 1
    self.y = 2

  class Child:
    def __init__(self, parent):
      self.parent = parent

    def parent_vars(self):
      att = self.parent.x

par = Parent()
child = Parent.Child(par)  # note how `Parent.Child`, not `par.Child()`
# 1