Rob
Rob

Reputation: 7121

Python import class to use as nested/inner class in another class

Python version:

Python 3.6

I have this class:

class Backup:
    class Create:
        @staticmethod
        def all():
            print('create all')

        @staticmethod
        def user(username):
            print('create user: ' + username)

        @staticmethod
        def file(filename):
            print('create file: ' + filename)

    class Restore:
        @staticmethod
        def all():
            print('restore all')

        @staticmethod
        def user(username):
            print('restore user: ' + username)

        @staticmethod
        def file(filename):
            print('restore file: ' + filename)

    class Delete:
        @staticmethod
        def all():
            print('delete all')

        @staticmethod
        def user(username):
            print('delete user: ' + username)

        @staticmethod
        def file(filename):
            print('delete file: ' + filename)

But I want to move the nested classes to their own modules and import them, but I am not sure how to do that. Here was my latest attempt based on some similar stack overflow questions. Obviously it didn't work:

from Models.Create import Create

class Backup(Create):

Does anyone know how to achieve what I am trying to do so I can still call the methods in the classes like this: Backup.Create.all()

Upvotes: 1

Views: 4717

Answers (1)

Brett Beatty
Brett Beatty

Reputation: 5993

One way to do it would be to import the inner classes within the outer.

class Backup:
    from Models.Create import Create
    from Models.Delete import Delete
    from Models.Restore import Restore

If you do it this way, I would import them all into the 'Models' package's __init__.py, so you could just do this:

class Backup:
    from Models import Create, Delete, Restore

Another option if you're importing them elsewhere is just assigning them within the class.

class Backup:
    Create = Models.Create.Create
    Delete = Models.Delete.Delete
    Restore = Models.Restore.Restore

Upvotes: 3

Related Questions