在python中覆盖__import__

时间:2015-06-21 13:19:03

标签: python initialization derived-class base-class

当我动态导入派生类时,我需要在python中覆盖__import__函数。 (我只能访问基类代码)。例如:

Servers=[]

class ServerBase(object):
    name='' #name of the specific server class, for each server class

    def __init__(self):
        self.connected = False
        self.name = self.__class__.__module__.capitalize()
        Servers.append(self)

导入派生类时,我需要调用基类的__init__将其添加到Servers []列表中,所以在主模块中我调用:

__import__('DerivedClassName')

将调用基础__init__

1 个答案:

答案 0 :(得分:2)

我最终在metaclassing Servers类:

Servers=[]

''' Servers Metaclass that handles addition of servers to the list '''
class MetaServer(type):
    def __init__(self, name, bases, attrs):
        self.name = name.capitalize()
        Servers.append(self)
        super(MetaServer, self).__init__(name, bases, attrs)

class ServerBase:
    __metaclass__ = MetaServer
    name='' #name of the specific server class, for each server class

    def __init__(self):
        self.connected = False

这样每次导入派生类时都会调用meta-init。 正是我想要的。 谢谢@MartijnPieters