Python implements the solution of dynamically adding class attributes or member functions

  • 2020-04-02 13:49:46
  • OfStack

Sometimes we need to have the class add properties or methods dynamically, as we do with plug-ins. Use a configuration file to specify the modules that need to be loaded, and you can add any required modules according to the business extension.

This paper briefly describes the solution of Python to dynamically add class attributes or member functions, the specific method is as follows:

First we can refer to the implementation of ulipad: mixins.

Here, it is relatively simple to declare a class, read the configuration file when the class is initialized, load the function under the module under the specific directory according to the configuration list, the function and the module have the same name, and dynamically load this function as the member function of the class.

The code is as follows:


class WinBAS(Bas):
  def __init__(self):
    self.__baslist = {}
    self.__Init_Modules()
    pass
  def __Init_Modules(self):
    import modplugs
    for m in modplugs.__moduleset__:
      mh = __import__('modules.' + m)# + '.' + m)
      ma = getattr(mh, m)# + '.' + m)
      ma = getattr(ma, m)
      setattr(self.__class__, m, ma)

Modplugs. Py is the module configuration file is as follows:


__moduleset__ = [
'BAS_GetUserList',
]

Next, set up an empty s/s file named s/s/s. Py, turn the directory into a package, and set up the actual BAS_GetUserList implementation in the modules directory.


def BAS_GetUserList(self, strs):
  return [0, strs]

This allows the WinBAS class to dynamically add the BAS_GetUserList function.


Related articles: