Populate a list of classes in python in the base class module

1.1k views Asked by At

I want to have a list of classes in the base class file which holds the derived classes as they are being created in runtime:

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

This is a real world example:

I am not able to modify any derived classes code so I want to maintain a list of added servers in the base class and then access this list in runtime

# 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")
1

There are 1 answers

0
Anand S Kumar On

Assuming what you want is a list of derived class objects (though no idea why you would want that) created at runtime.

When creating an object of a Derived class, in your Base Class's __init__ function, the self, being passed in would be the Derived class's object , Unless the derived class overrides the __init__() function and does not call super().__init() , in which case, I am not sure if it would be possible.

If you control the derived classes , you can call super().__init__() in the derived class' __init__() and then have the __init__() function save that object to the list as you want.

You can use that self to add to the list you want.

A simple test like below may help you -

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>

There may be better ways to do it, this would be one way.