Inner classes


An inner class or nested class is a defined entirely within the body of another class 

Inner class example

We create a class (Human) with one inner class (Head).
An instance is created that calls a method in the inner class:

#!/usr/bin/env python
 
class Human:
 
 def __init__(self):
    self.name = 'Guido'
    self.head = self.Head()
 
 class Head:
    def talk(self):
    return 'talking...'
 
if __name__ == '__main__':
    guido = Human()
    print guido.name
    print guido.head.talk()

Output:

Guido
talking...

In the program above we have the inner class Head() which has its own method. An inner class can have both methods and variables. In this example the constructor of the class Human (__init__) creates a new head object.  

Multiple inner classes

You are by no means limited to the number of inner classes, for example this code will work too:

#!/usr/bin/env python
 
class Human:
 
  def __init__(self):
    self.name = 'Guido'
    self.head = self.Head()
    self.brain = self.Brain()
 
  class Head:
    def talk(self):
      return 'talking...'
 
  class Brain:
    def think(self):
      return 'thinking...'
 
if __name__ == '__main__':
  guido = Human()
  print guido.name
  print guido.head.talk()
  print guido.brain.think()

By using inner classes you can make your code even more object orientated. A single object can hold several sub objects.  We can use them to add more structure to our programs.


6 thoughts on “Inner classes

  1. Bob - August 21, 2015

    Hi Frank,
    I was wondering how would we show a content of a variable defined in the parent class in the inner class?

    1. Frank - August 22, 2015

      As far as i know, inner classes have no way of accessing outer class variables.

  2. Adadion - June 22, 2015

    Hi Frank! I just wonder why __name__ here set to __main__?
    I can figure the guido.name, head.talk(), brain.think(), and the other parts and how it works.
    But I’m totally confuse, about __main__ condition.
    Is it because __name__ is private variable?
    What if I replace __main__ here with __main, like your example variable structure in encapsulation?
    An answer will be valuable to me.
    Ps. I’m just totally beginner, but your tutorial are the easiest one to be understood.
    Thank’s

    1. Frank - June 22, 2015

      Hi! Thanks! Python has an execution entry point called main. When you execute a Python script, it is used as the main function (starting point of the program) if the __name__ attribute is set to “__main__”.

      If you import this script as a module, the __name__ is set to the name of the script/module and it will not be executed.

      The code below is used to execute some code only if the file was run directly, and not imported.

      if __name__ == "__main__":
          # execute only if run as a script
          main()

      Let us do an example, we create a python file called file.py:

      #!/usr/bin/env python
       
      if __name__ == "__main__":
          print 'Hello from file.py'

      And file2.py:

      import file
       
      if __name__ == "__main__":
          print 'Hello from file2.py'

      If we run either of these two scripts, it will execute only the code in __main__. Thus the output is either “Hello from file.py” or “Hello from file2.py”.
      However, if we change file.py to:

      #!/usr/bin/env python
       
      print 'Hello from file.py'

      and run file2.py, it will execute all code in file.py and in the __main__ of file2.py, thus outputting:

      Hello from file.py
      Hello from file2.py

      In short, we need __main__ if we want to couple python files together. Without __main__, Python will execute all code from every file that is imported.
      If you change to __main it will not execute or use it as starting point of a script because __main__ is a special variable in Python.

      That means that you do not have to use __main__ at all if you are not importing the script anywhere, meaning this will work too:

      #!/usr/bin/env python
       
      class Human:
       
        def __init__(self):
          self.name = 'Guido'
          self.head = self.Head()
          self.brain = self.Brain()
       
        class Head:
          def talk(self):
            return 'talking...'
       
        class Brain:
          def think(self):
            return 'thinking...'
       
      guido = Human()
      print guido.name
      print guido.head.talk()
      print guido.brain.think()
      1. Adadion - June 25, 2015

        In your (files).py examples, if the __main__ code in file.py are removed, it will make file.py become regular class, and file2.py become the main class, like in Java?
        If that so, in my mind, simple Java program always have main class (public static void main) that will execute the listed program, while in python some simple program didn’t always need __main__ to execute the listed program.
        Am I correct?
        Sorry, completely new to python world, and totally forgot java environment after years.
        Thank’s for your patience, Frank!

        1. Frank - June 25, 2015

          Yes, if __main__ is removed, file.py will become a regular class. Python will execute anything that is on the 0th level of indention from file.py, which is different form Java. If file.py would contain a class with methods, it can be included without any problems. The code below demonstrates:

          file.py

          #!/usr/bin/env python
           
          class Test:
              def test(self):
                  print 'Hello from file.py'

          file2.py

          from file import *
           
          if __name__ == "__main__":
              print 'Hello from file2.py'
              t = Test()
              t.test()

          In usage its similar to Java’s public static void main, with the exception that Python will execute any statement on the 0th level of indention.