Inner Classes: How can I get the outer-class object at construction time?

前端 未结 7 830
死守一世寂寞
死守一世寂寞 2020-12-08 23:15

Consider the following Python (runs in 2.x or 3.x):

class Outer(object):
  pass

  class Inner(object):
    def __init__(self):
      print(\"Inner.self\", s         


        
相关标签:
7条回答
  • 2020-12-09 00:18

    Can't be done. But with a bit of redesign:

    class Outer(object):
      pass
    
      class _Inner(object):
        def __init__(self, outobj):
          self.outobj = outobj
    
      def Inner(self):
        return self._Inner(self)
    
    o = Outer()
    i = o.Inner()
    
    print o, i.outobj
    
    0 讨论(0)
提交回复
热议问题