Python realizes the method analysis of dynamically loading modules classes and functions

  • 2020-06-12 09:47:33
  • OfStack

An example of Python shows how to load modules, classes and functions dynamically. To share for your reference, specific as follows:

Dynamic loading module:

Method 1: system function with ___
Method 2: imp, importlib module
Method 3: exec function

Dynamically loading classes and functions

First, use the load module, using getattr(), the reflection method provided by the built-in function, to get the module - in turn by hierarchy > Class \ global methods - > Class objects \ class methods.

test_import_module.py


class ClassA:
  def test(self):
    print('test')
  int_value = 1
  str_value = __author__
#  Global method, which is called when loaded 
print(__file__, 'global function.')
if __name__ == '__main__':
  print(__file__, __name__)

test_import_module.py


#  Note: Module names are not included .py The suffix 
imp_module = 'test_import_class'
imp_class = 'ClassA'
#  way 1 Use: __import__() The import module 
#  Import the specified module, when which global methods are executed. 
ip_module = __import__(imp_module)
# dir() View module properties 
print(dir(ip_module))
#  use getattr() To obtain imp_module The class of 
test_class = getattr(ip_module, imp_class)
#  Dynamically loaded class test_class Generate class objects 
cls_obj = test_class()
#  View object properties 
print(dir(cls_obj))
for attr in dir(cls_obj):
  #  To load the __ Properties of prefixes 
  if attr[0] != '_':
    #  To obtain import obj Methods. 
    class_attr_obj = getattr(cls_obj, attr)
    #  Determines whether a class attribute is a function 
    if hasattr(class_attr_obj, '__call__'):
      #  Executive function 
      class_attr_obj()
    else:
      #  Output class attribute values 
      print(attr, ' type:', type(class_attr_obj), ' value:', class_attr_obj)

The output


D:/work/python\test_import_class.py global function.
['ClassA', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'int_value', 'str_value', 'test']
int_value type: <class 'int'> value: 1
str_value type: <class 'str'> value: abc
test


#  way 2 Use: importlib
# importlib Compared with the __import__() , the operation is more simple, flexible, support reload()
import importlib
ip_module = importlib.import_module('.', imp_module)
ip_module_cls = getattr(ip_module, imp_class)
cls_obj = ip_module_cls()
if 'int_value' in dir(cls_obj):
  print(cls_obj.int_value)
  cls_obj.int_value = 10
  print(cls_obj.int_value)
# reload() Reload, 1 Generally used in the original module changes and other special circumstances. 
# reload() The module must already be in use import Import the module. 
#  Reload the module, but the original used instance will still use the old module, and the new production instance will use the new module, reload I'm going to use the same memory address. 
ip_module = importlib.reload(ip_module)
print(getattr(ip_module, imp_class).int_value)
#  Repeatedly load the same file, manually modify the file data, found that the reload output content changes. 
from time import sleep
for i in range(30):
  ip_module = importlib.reload(ip_module)
  print(getattr(ip_module, imp_class).int_value)
  sleep(3)

For more information about Python, please refer to Python Coding Skills Summary, Python Data Structure and Algorithm Tutorial, Python Function Skills Summary, Python String Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: