python内部类的用途是什么?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (210)

Python的内部/嵌套类使我感到困惑。有没有什么东西没有它们是无法完成的?如果有,那是什么?

提问于
用户回答回答于

引用自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.
用户回答回答于

有没有什么东西没有它们是无法完成的?

没有。它们完全等同于通常在顶层定义类,然后将对它的引用复制到外部类中。

扫码关注云+社区

领取腾讯云代金券