Python Dynamic call module, class, Method (Django project)

Source: Internet
Author: User

Requirements: In recent time based on the Django framework, the development of various business layer monitoring code, each business monitoring logic is different, so need to develop monitoring sub-modules, dynamic import calls.

Project Name: Demo_django

App:common_base, Monitor_master

Monitoring sub-module: demo_django/common_base/modules/classname.py

#-*-Coding:utf-8-*-class ClassName (object):d EF mod1 (self):p rint "Mod1" def mod2 (self):p rint "Mod2"

Note: The module name is the same as the class name

dynamic application module: Demo_ django/common_base/module_partiton.py

def test ():    clsname = "ClassName"    method = "Mod1" Importmodule = Lazyimport ("monitor_base.modules." + Clsname, Clsname)  # import classname Module is_true = hasattr (Importmodule, clsname)  # Check if classname class is in classname module if is_true: classname = GetAttr (Importmodule, clsname) obj = classname (self.hostlist, Self.way)  # instantiates classname class MTD = GetAttr (obj , method) MTD ()  # calls the Mod1 method class Lazyimport (object): "" "    Dynamic Import Module" "    def __init__ (self, module_ Name, Module_class): "" "        :p Aram module_name:        :p Aram Module_class:        : return: equivalent to form module_name Import Module_class ""        "        self.module_name = module_name        self.module_class = Module_class        Self.module = None    def __getattr__ (self, name):        if Self.module is none:            self.module = __import__ ( Self.module_name, Fromlist=[self.module_class])        return getattr (self.module, name) if __name__ = = ' __main__ ':      Test ()

Reference: http://www.cnblogs.com/bluefrog/archive/2012/05/11/2496439.html

Python Dynamic call module, class, Method (Django project)

Related Article

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.