class within a class python code example

Example 1: muitiple inner classes in python

class Outer:
    """Outer Class"""

    def __init__(self):
        ## Instantiating the 'Inner' class
        self.inner = self.Inner()
        ## Instantiating the '_Inner' class
        self._inner = self._Inner()

    def show_classes(self):
        print("This is Outer class")
        print(inner)
        print(_inner)

    class Inner:
        """First Inner Class"""

        def inner_display(self, msg):
            print("This is Inner class")
            print(msg)

    class _Inner:
        """Second Inner Class"""

        def inner_display(self, msg):
            print("This is _Inner class")
            print(msg)

    ## ...

Example 2: nested classes in python

## outer class
class Outer:

    ## inner class
    class Inner:
        pass

        ## multilevel inner class
        class InnerInner:
            pass

    ## another inner class
    class _Inner:
        pass

    ## ...

    pass

Example 3: how to create a class inside a function in python

def create_class():
  class Person:
    def __init__(self, name, age):
      self.name = name
      self.age = age
      
  # returns the class NOT an instance of the class
  # instance would be Person()
  return Person

my_class = create_class()
person1 = my_class("John", 24)

print(f'{person1.name} is {person1.age} years old.')