This article mainly introduces how to dynamically add class attributes or member functions in Python, which will be useful in development similar to plug-ins, for more information about how to add attributes or methods to a class dynamically, for example, we can use this method when doing plug-ins. Use a configuration file to specify the modules to be loaded. you can add the required modules as needed.
This article briefly describes how to dynamically add class attributes or member functions in Python. the specific methods are as follows:
First, we can refer to the ulipad implementation: mixin.
This is relatively simple. it just declares a class. when the class is initialized, it reads the configuration file and loads the functions under the modules in a specific directory according to the configuration list. the functions have the same name as the modules, dynamically load this function as a 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 as follows:
__moduleset__ = ['BAS_GetUserList',]
Create an empty _ init _ under the modules Directory __. py file to change the directory into a package, and create a real BAS_GetUserList under the modules Directory. the BAS_GetUserList function in the BAS_GetUserList file is as follows:
def BAS_GetUserList(self, strs): return [0, strs]
In this way, the WinBAS class can dynamically add the BAS_GetUserList function.