Nested Python class needs to access variable in enclosing class

前端 未结 6 2235
难免孤独
难免孤独 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:29

    Well, the following works (further simplified from your example). Note that you don't have to "declare" member variables at class level like C++/C#/Java etc, just set them on self within __init__:

    class ParentClass:
        def __init__(self):
            self.constant_pool = ["test"]
            self.ChildClass.constant_pool = self.constant_pool
            self.children = [self.ChildClass()]
    
        class ChildClass:
            def __init__(self):
                self.name = self.constant_pool[0]
                print "child name is", self.name
    
    p = ParentClass() # Prints "child name is test"
    

    Note that you could still do the same sort of thing without the child classes being nested.

提交回复
热议问题