获取几个python模块中定义的所有子类

时间:2015-12-07 15:56:58

标签: python python-2.7 oop subclass

我有2个python文件实现测试库工厂模式:

testrepository.py

class TestRepository(object):
    def __init__(self):
        pass

    def generate(self, username, password):
        pass

    def update(self):
        pass

class RepositoryFactory(object):
    factories = {}

    def add_repo(identification, repo_factory):
        RepositoryFactory.factories[identification] = repo_factory
    add_repo = staticmethod(add_repo)

    def create_repo(identification, server, dirpath, reponame):
        if identification not in RepositoryFactory.factories:
            RepositoryFactory.factories[identification] = \
                eval(identification + '.Factory()')
        return RepositoryFactory.factories[identification].create(server, dirpath, reponame)
    create_repo = staticmethod(create_repo)

gitrepository.py

from testrepository import TestRepository, RepositoryFactory

class GitRepository(TestRepository):
    def __init__(self, server, dirpath, reponame):
        super(GitRepository, self).__init__()
        self.server = server
        self.dirpath = dirpath
        self.reponame = reponame
        self.username = None
        self.password = None
        self.fullPath = path.join(self.dirpath, self.reponame)

    def generate(self, username, password):
        pass

    def update(self):
        pass

    class Factory(object):
        @staticmethod
        def create(server, dirpath, reponame):
            return GitRepository(server=server, dirpath=dirpath, reponame=reponame)

if __name__ == '__main__':
    repo_type = TestRepository.__subclasses__().pop().__name__
    repo = RepositoryFactory.create_repo(repo_type,
                                         server='localhost',
                                         dirpath='/home/user/git',
                                         reponame='repo')
    repo.generate(username='test', password='test')
    repo.update()

问题是 repo_type = TestRepository .__子类__() 在上面的例子中是空的,如果我将所有类放在一个文件中就可以了:

>>> print TestRepository.__subclasses__()
[<class '__main__.GitRepository'>]

所以问题是如何从几个python模块中获取所有子类?

0 个答案:

没有答案