Summary of python dynamic loading methods and python Dynamic Loading

Source: Internet
Author: User

Summary of python dynamic loading methods and python Dynamic Loading

This example summarizes the python dynamic package loading method. We will share this with you for your reference. The details are as follows:

Three methods are available for Dynamic Loading modules.

1. Use System Function _ import _()

stringmodule = __import__('string')

2. Use the imp Module

import imp stringmodule = imp.load_module('string',*imp.find_module('string'))imp.load_source("TYACMgrHandler_"+app.upper(), filepath)

3. Use exec

import_string = "import string as stringmodule"exec import_string

Whether the variable exists

1. hasattr (Test, 'T ')
2. 'var 'in locals (). keys ()
3. 'var' in dir ()
4. vars (). has_key ('s ')

Dynamically add attributes

class Obj(object):  passdef main():  list=["a","b", "c"]  for i inrange(1,len(list),2):    Obj = type('Obj',(),{list[i]:lambdaself,s:obj.__setattr__(s.split(" = ")[0],s.split(" = ")[1])})  obj =Obj()  for i inrange(0,len(list),2):    obj.__setattr__(list[i],list[i])    obj.a =1  obj.b("a =2")  obj.b("c =3")  printobj.a  printobj.cif __name__ == '__main__':  main()

Dynamic Package loading:

def test(s,e):  print s  print eclass C():  def __init__(self,name):    print name  def test(self):    print 'class!!!'

Loader code:

class Dynload():  def __init__(self,package,imp_list):    self.package=package    self.imp=imp_list  def getobject(self):    return __import__(self.package,globals(),locals(),self.imp,-1)  def getClassInstance(self,classstr,*args):    return getattr(self.getobject(),classstr)(*args)    def execfunc(self,method,*args):    return getattr(self.getobject(),method)(*args)  def execMethod(self,instance,method,*args):    return getattr(instance,method)(*args)#Test:dyn=Dynload('util.common',['*'])ins=dyn.getClassInstance('C','gao')dyn.execMethod(ins,'test')dyn.execfunc('test','Hello','function!')

Load a specified file by name

Def loadapp (self, app): filepath = "mgr/" + app + ". py "if OS. path. exists (filepath): imp. load_source ("TYACMgrHandler _" + app. upper (), filepath) // modified the app. py: Call this function again, and the new Code will automatically take effect.

Call the corresponding method by name

return getattr(self, op)(args.get("port"), args) //op="start" args=dictgetattr(self, self.request.method.lower())(*args, **kwargs)

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.