繁体   English   中英

在基类模块中填充python中的类列表

[英]Populate a list of classes in python in the base class module

我想在基类文件中有一个类列表,其中包含在运行时中创建的派生类:

BaseClass.py:

# This is a list of objects to populate, holds classes (and not instances)
MyClassesList=[]

class MyBase(object):
    name='' #name of the specific derived class

    def __init__(self):
        pass

这是一个真实的例子:

我无法修改任何派生类代码,因此我想维护基类中已添加服务器的列表,然后在运行时访问此列表

# Populate the Servers list automatically.
# This is a list of available servers to choose from, holds classes (and not instances)

Servers=[]

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

    def __init__(self):
        self.connected = False

    def __del__(self):
        self._disconnect()

    def connect(self):
        DBG("connect called for server {self.name}, is already connected: {self.connected}")
        if self.connected: return
        self._connect()
        self.connected = True


    def get_data(self):
        self.connected or self.connect()
        data=''
        # We're obligated to read the data in chunks.
        for i in range(100):
            data += self._get_data()
        return data

    def _connect(self):
        raise NotImplementedError("Interface Function Called")

    def _disconnect(self):
        raise NotImplementedError("Interface Function Called")

    def _get_data(self):
        raise NotImplementedError("Interface Function Called")

假设您想要的是在运行时创建的派生类对象的列表(尽管不知道为什么要这么做)。

在创建派生类的对象时,在基类的__init__函数中,传入的自身将是派生类的object,除非派生类重写__init__()函数且不调用super().__init() ,在这种情况下,我不确定是否可能。

如果控制派生类,则可以在派生类的__init__()调用super().__init__() __init__() ,然后让__init__()函数根据需要将该对象保存到列表中。

您可以使用该self添加到所需列表。

如下所示的简单测试可能会帮助您-

class CA:
    def __init__(self):
        print('Type - ' + str(type(self)))

>>> CA()
Type - <class '__main__.CA'>
<__main__.CA object at 0x006B9830>



class CASub(CA):
    pass

>>> CASub()
Type - <class '__main__.CASub'>
<__main__.CASub object at 0x006B9890>

可能会有更好的方法来做,这只是一种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM