What is the purpose of python's inner classes?

前端 未结 9 1175
心在旅途
心在旅途 2020-11-28 02:12

Python\'s inner/nested classes confuse me. Is there something that can\'t be accomplished without them? If so, what is that thing?

9条回答
  •  萌比男神i
    2020-11-28 02:52

    There's something you need to wrap your head around to be able to understand this. In most languages, class definitions are directives to the compiler. That is, the class is created before the program is ever run. In python, all statements are executable. That means that this statement:

    class foo(object):
        pass
    

    is a statement that is executed at runtime just like this one:

    x = y + z
    

    This means that not only can you create classes within other classes, you can create classes anywhere you want to. Consider this code:

    def foo():
        class bar(object):
            ...
        z = bar()
    

    Thus, the idea of an "inner class" isn't really a language construct; it's a programmer construct. Guido has a very good summary of how this came about here. But essentially, the basic idea is this simplifies the language's grammar.

提交回复
热议问题