What is the purpose of python's inner classes?

前端 未结 9 1198
心在旅途
心在旅途 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条回答
  •  盖世英雄少女心
    2020-11-28 03:05

    Quoted from http://www.geekinterview.com/question_details/64739:

    Advantages of inner class:

    • Logical grouping of classes: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
    • Increased encapsulation: Consider two top-level classes A and B where B needs access to members of A that would otherwise be declared private. By hiding class B within class A A's members can be declared private and B can access them. In addition B itself can be hidden from the outside world.
    • More readable, maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.

    The main advantage is organization. Anything that can be accomplished with inner classes can be accomplished without them.

提交回复
热议问题