Simple example
A nested class can be created and used outside the class that it contains by fully qualifying its name:
#!/usr/bin/python3
class TQ84():
class Nested():
def __init__(self, name):
self.name = name
def __str__(self):
return 'TQ84.Nested, name = ' + self.name
n = TQ84.Nested('foo')
print(n)
#
# TQ84.Nested, name = foo
Fully qualified name required
Interestingly, even if the nested class is used within the class that contains it, its name still needs to be fully qualifed (in the following example, that is either self.Nested
or CLS.Nested
):
#!/usr/bin/python3
class CLS():
class Nested():
def __init__(self, name):
self.name = name
def __str__(self):
return 'CLS.Nested, name = ' + self.name
def __init__(self, name, name_nested):
self.name = name
#
# Note: Even though B.Nested is nested within
# class B, Nested needs to be qualified with
# either self.Nested or B.Nested!
#
self.nested = CLS.Nested(name_nested)
def __str__(self):
return 'CLS, name = ' + self.name + ' - ' + str(self.nested)
inst = CLS('bar', 'baz')
print(inst)
#
# CLS, name = bar - CLS.Nested, name = baz