Back to: Python Programming
0
Nested classes in Python, also known as inner classes, are classes defined within the scope of another class. This structure offers a way to logically group related classes and manage their scope within an object-oriented program.
Key characteristics and uses of nested classes:
- Logical Grouping: Nested classes are primarily used to group classes that are conceptually dependent on or closely related to an outer class. For example, a
Carclass might contain anEngineclass if theEngineis considered an integral part of theCarand is not intended to be used independently. - Encapsulation and Scope Management: By nesting a class, its scope is limited to the outer class. This can help in encapsulating implementation details and preventing naming conflicts in the global namespace. An inner class is typically not meant for direct instantiation outside of the outer class’s context.
- Accessing Outer Class Members: An instance of a nested class can access attributes and methods of its enclosing outer class, often through a reference to the outer class instance that created it.
- Creating Instances: To create an instance of a nested class, you typically access it through the outer class, such as
OuterClass.InnerClass(). If an instance of the outer class is needed to create the inner class instance, it would beouter_object.InnerClass().
class Car:
def __init__(self, make, model):
self.make = make
self.model = model
self.engine = self.Engine() # Create an instance of the nested class
def start_car(self):
print(f"Starting the {self.make} {self.model}.")
self.engine.start()
class Engine:
def __init__(self):
self.cylinders = 8
self.horsepower = 1200
def start(self):
print(f"Engine with {self.cylinders} cylinders and {self.horsepower} HP is starting.")
# Create an instance of the outer class
my_car = Car("Chevrolet", "Corvette")
# Accessing a method of the outer class, which in turn uses the inner class
my_car.start_car()
# Directly accessing and creating an instance of the nested class (less common)
# separate_engine = Car.Engine()
# separate_engine.start()
Outputs:
Starting the Chevrolet Corvette.
Engine with 8 cylinders and 1200 HP is starting.