Nested Python class needs to access variable in enclosing class

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

    Despite my "bit patronizing" comment (fair play to call it that!), there are actually ways to achieve what you want: a different avenue of inheritance. A couple:

    1. Write a decorator that introspects a class just after it's declared, finds inner classes, and copies attributes from the outer class into them.

    2. Do the same thing with a metaclass.

    Here's the decorator approach, since it's the most straightforward:

    def matryoshka(cls):
    
        # get types of classes
        class classtypes:
            pass
        classtypes = (type, type(classtypes))
    
        # get names of all public names in outer class
        directory = [n for n in dir(cls) if not n.startswith("_")]
    
        # get names of all non-callable attributes of outer class
        attributes = [n for n in directory if not callable(getattr(cls, n))]
    
        # get names of all inner classes
        innerclasses = [n for n in directory if isinstance(getattr(cls, n), classtypes)]
    
        # copy attributes from outer to inner classes (don't overwrite)
        for c in innerclasses:
            c = getattr(cls, c)
            for a in attributes:
                if not hasattr(c, a):
                    setattr(c, a, getattr(cls, a))
    
        return cls
    

    Here is a simple example of its use:

    @matryoshka
    class outer(object):
    
        answer = 42
    
        class inner(object):
    
            def __call__(self):
                print self.answer
    
    outer.inner()()   # 42
    

    However, I can't help but think some of the ideas suggested in other answers would serve you better.

提交回复
热议问题