Python导入类在另一个类中用作嵌套/内部类

时间:2017-12-13 05:25:49

标签: python python-3.x class inner-classes

Python版本:

Python 3.6

我有这堂课:

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)

但我想将嵌套类移动到他们自己的模块并导入它们,但我不知道该怎么做。这是我基于一些类似的堆栈溢出问题的最新尝试。显然它没有用:

from Models.Create import Create

class Backup(Create):

有谁知道如何实现我想要做的事情,所以我仍然可以调用类中的方法:Backup.Create.all()

1 个答案:

答案 0 :(得分:2)

一种方法是在外部导入内部类。

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

如果您这样做,我会将它们全部导入到'模型' package' s __init__.py,所以你可以这样做:

class Backup:
    from Models import Create, Delete, Restore

如果您将其他地方导入其他地方,另一种选择就是在课堂上分配它们。

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