python中动态加载模块和类方法实现

2023-01-31 05:01:08 模块 方法 加载

python中动态加载模块和类方法实现测试代码

 

文件名: mytest.py 具体代码如下:

 

注意:模块名,类名,方法名都是变量。

 

#coding=UTF-8


class TestClass:
    def sub(self,a,b):
        return a-b
    def add(self,a,b):
        return a+b
    def echo(self):
        print "test"

def main():
    class_name = "TestClass" #类名
    module_name = "mytest"   #模块名
    method = "echo"          #方法名

    module = __import__(module_name) # import module
    print "#module:",module
    c = getattr(module,class_name)  
    print "#c:",c
    obj = c() # new class
    print "#obj:",obj
    print(obj)
    obj.echo()
    mtd = getattr(obj,method)
    print "#mtd:",mtd
    mtd() # call def
    
    mtd_add = getattr(obj,"add")
    t=mtd_add(1,2)
    print "#t:",t

    mtd_sub = getattr(obj,"sub")
    print mtd_sub(2,1)
    
  
    

if __name__ == '__main__':
   main()


执行后输出如下:

 

> "D:\Python27\python.exe"  "D:\test\src\mytest.py"
#module: <module 'mytest' from 'D:\test\src\mytest.py'>
#c: mytest.TestClass
#obj: <mytest.TestClass instance at 0x025F2AA8>
<mytest.TestClass instance at 0x025F2AA8>
test
#mtd: <bound method TestClass.echo of <mytest.TestClass instance at 0x025F2AA8>>
test
#t: 3
1

相关文章