Classes in a class: how to access variables from one in another

Steven D'Aprano steve at
Tue Oct 19 00:20:14 CEST 2010

On Mon, 18 Oct 2010 17:17:52 +0200, Christian Heimes wrote:

> Don't nest classes. Just don't. This might be a valid and good approach
> in some programming languages but it's not Pythonic. Your code can
> easily be implemented without nested classes.

I'll accept that nested classes are unusual, but unPythonic? Never! 
Here's a contrived example:

class K:
    class Data(tuple):
        def __init__(self, t):
            a, b, c = t
            self.a = a
            self.b = b
            self.c = c
    def spam(self, a, b, c): = type(self).Data([a,b,c])

Of course, in Python 2.6 this *specific* example is better written using 
namedtuple, but namedtuple is just a factory function for returning a 

class K:
    # One-liner to create a nested class.
    Data = namedtuple("Data", "a b c")

Either way, now you can subclass K by changing Data, without exposing 
your private, internal classes to the rest of the module:

class K2(K):
    class Data(K.Data):
        def __init__(self, t):
            t = (int(x) for x in t)
            super(Data, self).__init__(t)


More information about the Python-list mailing list