How to dynamically add class attributes or member functions in Python

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.