What is the purpose of python's inner classes?

前端 未结 9 1199
心在旅途
心在旅途 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:06

    Nesting classes within classes:

    • Nested classes bloat the class definition making it harder to see whats going on.

    • Nested classes can create coupling that would make testing more difficult.

    • In Python you can put more than one class in a file/module, unlike Java, so the class still remains close to top level class and could even have the class name prefixed with an "_" to help signify that others shouldn't be using it.

    The place where nested classes can prove useful is within functions

    def some_func(a, b, c):
       class SomeClass(a):
          def some_method(self):
             return b
       SomeClass.__doc__ = c
       return SomeClass
    

    The class captures the values from the function allowing you to dynamically create a class like template metaprogramming in C++

提交回复
热议问题