python的内部类的目的是什么? [英] What is the purpose of python's inner classes?

查看:1544
本文介绍了python的内部类的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的内部/嵌套类混淆了我。有没有没有他们不能完成的事情?如果是,那是什么东西?

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

推荐答案

引用 http://www.geekinterview.com/question_details/64739


内部类的优点:




  • 类的逻辑分组:如果一个类只对一个其他类有用那么将它嵌入到该类中并将它们保存在一起是合乎逻辑的。嵌套此类帮助类可使其包更简化。

  • 增加封装:考虑两个顶级类A和B,其中B需要访问A否则将被声明为私有。通过在类A中隐藏类B A的成员可以被声明为私有的,B可以访问它们。
  • :在顶级类中嵌套小类可将代码更接近于

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.

这篇关于python的内部类的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆