Cryphakon
Cryphakon

Reputation: 59

Python: Inner classes with subclass inheritance?

Is it possible to have inheritance for inner classes like it is with subclass(object)? How would I do it with the below code for instance?

class main:
    class sub(main):
        def __init__(self):
            print(main.foo)
    def __init__(self):
        self.foo = "bar"
        baz = self.sub()

if __name__ == '__main__':
    bar = main()

Upvotes: 3

Views: 2687

Answers (1)

Evan
Evan

Reputation: 2357

It is kind of confusing what you are looking for, in particular do you want instances of main and sub to be 'nested' or do you actually want nested classes, which is a very unusual thing to want. You can't have a nested class that subclasses its enclosing

You can replicate what I think you are trying to do with simple composition:

class Main(object):
    def __init__(self):
        self.foo = 'bar'
        baz = Helper(self)

class Helper(object):
    def __init__(self, parent):
        self.parent = parent  
        print(parent.foo) # Access to members of Main through parent reference

if __name__ == "__main__":
    x = Main()

I have called the auxiliary class helper because it is not a subclass, it is just a helper class. This is a bit dubious. If these two classes are so tightly coupled there is always a 1:1 relationship between them and they both need to hold references to the other, it isn't clear why they are separate classes. You can also do something similar with regular inheritance, and I think this might be more like what you want.

class Main(object):
    def __init__(self):
        self.foo = 'bar'
class Sub(main):
    def __init__(self):
        super(Sub, self).__init__()
        print(self.foo)  # All attributes defined by main exist in sub
if __name__ == "__main__":
    Sub()

Notice that we construct the sub object which contains all the behavior from the main class as well as its own. Anyway, I hope this helps. If you can update your question to explain how the behavior you want differs from these, we can go from there.

Upvotes: 1

Related Questions