[ACCEPTED]-Using super() in nested classes-super

Accepted answer
Score: 20

I'm not sure why A.B is not working correctly 2 for you, as it should.. Here's some shell 1 output that works:

>>> class A(object):
...   class B(object):
...     def __init__(self):
...       super(A.B, self).__init__()
...   def getB(self):
...     return A.B()
... 
>>> A().getB()
<__main__.B object at 0x100496410>
Score: 5

Since B will likely never be extended itself, this 1 should work:

class A(object):
    class B(object):
        def __init__(self):
            super(self.__class__, self).__init__()
Score: 2

If the class A.B is unlikely to participate 9 in any multiple inheritance, then you're 8 better off just hard-coding the constructor 7 call:

class A(object):
    class B(object):
        def __init__(self):
            object.__init__(self)

But if you really do need to have the 6 full power of super, then you can get what 5 you want by defining a custom descriptor 4 that will initialize the B attribute lazily:

class LazyAttribute(object):
    def __init__(self, func, *args, **kwargs):
        self._func = func
        self._args = args
        self._kwargs = kwargs
        self._value = None

    def __get__(self, obj, type=None):
        if self._value is None:
            print 'created', self._value
            self._value = self._func(*self._args, **self._kwargs)
        return self._value

class A(object):
    class B(object):
        def __init__(self):
            super(A.B, self).__init__()

    someattribute = LazyAttribute(B)

This 3 will cause the B attribute to be instantiated 2 the first time it's accessed, and then reused 1 thereafter:

>>> print A.someattribute
created <__main__.B object at 0x00AA8E70>
<__main__.B object at 0x00AA8E90>
>>> print A().someattribute
<__main__.B object at 0x00AA8E90>

For more info on descriptors, see: http://users.rcn.com/python/download/Descriptor.htm

More Related questions