Nested Python class needs to access variable in enclosing class

前端 未结 6 2238
难免孤独
难免孤独 2020-12-20 13:02

I\'ve seen a few \"solutions\" to this, but the solution every time seems to be \"Don\'t use nested classes, define the classes outside and then use them normally\". I don\'

6条回答
  •  粉色の甜心
    2020-12-20 13:12

    Another alternative design to consider:

    When you find yourself trying to use classes as namespaces, it might make more sense to put the inner classes into a module of their own and make what were the attributes of the outer class global variables. In other words, if you never intend to instantiate your ParentClass, then it's just serving as a glorified module.

    Global variables get a bad rap in most programming languages, but they are not truly global in Python, and are nicely encapsulated to the module.

提交回复
热议问题