Defining a class within another class in Python is a feature known as inner classes or nested classes. This concept allows you to declare a class inside another class, creating a tight association between the two. Inner classes are often used to encapsulate behavior within a class or to represent scenarios where an inner class is only meaningful in the context of its containing class.

The syntax for defining a class within another class in Python is straightforward. The inner class is declared as any regular class, using the keyword 'class', followed by the class name and the colon character inside the containing class.

Creating Inner Classes in Python
Here's a basic example demonstrating the creation of an inner class in Python:

class OuterClass: # The outer class
def __init__(self, outer_attr):
self.outer_attr = outer_attr
class InnerClass: # The inner class
def __init__(self, inner_attr):
self.inner_attr = inner_attr
Accessing Inner Class Attributes

To access an attribute from the outer class within the inner class, you can use the outer class instance to reference the attribute:
outer_instance = OuterClass('Outer Attribute')
inner_instance = outer_instance.InnerClass('Inner Attribute')
print(inner_instance.inner_attr, outer_instance.outer_attr)
This prints: Inner Attribute Outer Attribute

Using the 'self' Keyword in Inner Classes
In Python, 'self' is used as a reference to the instance of the class. When defining a method within an inner class, 'self' is used to access or change the Attributes or other methods of the inner class instance.
However, 'self' in an inner class always refers to the instance of the inner class itself, unlike in outer classes where 'self' refers to the instance of the outer class.

Types of Inner Classes in Python
Python supports two types of inner classes: non-local and local inner classes.




















Non-local inner classes: These can access the outer class instance variables directly. They are declared using the standard class definition syntax inside the outer class.
Non-local Inner Class Example
class OuterClass:
def __init__(self):
self.outer_attribute = 'non-local inner class'
class InnerClass:
def access_outer(self):
print(self.outer_attribute)
When an instance of InnerClass calls InnerClass().access_outer(), it prints 'non-local inner class'.
Local Inner Classes
These are defined within the scope of a method, loop, or other block of code. They can only access the first-level enclosing scope and their own scope.
Note: Starting from Python 3, local classes are restricted to methods in the sense that they can only access the 'nonlocal' and 'global' scopes. They cannot reference instance variables from the enclosing class or local variables.
Now that you have a good grasp on defining classes within classes in Python, you can explore more complex use-cases and take your coding skills to the next level. Happy coding!