【Python】getattr() 函数 动态导入模块、类、方法

动态导入类属性、类方法

# coding:utf-8
class run:
    # 类属性
    c1 = "class"
    # 函数
    def run_a(self, a):

        return a+1
    # 函数
    def run_b(self, b):

        return b*2

    def __init__(self):
        self.v1 = "123"

if __name__ == "__main__":
   
    x = run()
    
    dynamic = getattr(x, "c1")
    print("类属性:", dynamic)
   
    dyn_runa = getattr(x, "run_a")
    print("类中的函数:",dyn_runa(5))
    print("构造函数中的属性:", getattr(x, "v1"))

    
    dyn_runa = getattr(x, "run_b")
    print("构造函数中的属性:", getattr(x, "run_b")(5))

 

运行结果

 

 

 

不同类中导入类

# coding:utf-8
class run:
    # 类属性
    c1 = 8
    # 函数
    def run_a(self, a, b):

        return a*b
    # 函数
    def run_b(self, b):

        return b/2

    def __init__(self):
        self.v1 = "123"

class imp:
    run = run()
    c1 = getattr(run, "c1")
    # print("导入run类中的属性c1:", c1)

    imp_funa = getattr(run, "run_a")
    print("导入run类中的函数run_a:", imp_funa(100, c1))

    imp_funb = getattr(run, "run_b")
    # print("导入run类中的函数run_b:", imp_funb(100))


if __name__ == "__main__":
    print(imp().imp_funa(100, 20))

 

运行结果

 

 

 

 

# coding:utf-8
class run_casea:
    # 类属性
    c1 = 8
    # 函数
    def run_a(self, a, b):

        return a*b
    # 函数
    def run_b(self, b):

        return b/2

    def __init__(self):
        self.v1 = "123"

class sameC:
    test_a = run_casea()
    test = getattr(test_a, "run_a")

if __name__ == "__main__":

    print(sameC().test(5, 6))
run_casea.py

 

跨文件导入类

run_caseb.py

# coding:utf-8
import importlib

class run_caseb:
    bala = "balabalabala"

    def fun_a(self):
        return True

    def fun_i(self,):
        name = "a"
        case_name = "casea"
        # 导入run_case1 模块中run类
        imp_class = getattr(importlib.import_module("deploy.a.run_%s" % case_name), "run_%s" % case_name)
        # 导入run_case1 模块中run类中的属性c1
        attr = imp_class.c1
        print("c1 属性:", attr)
        # 导入run_case1 模块中run类中的方法run_a
        imp_fun = getattr(imp_class, "run_%s" % name)(self, 3, 4)
        return imp_fun


if __name__ == "__main__":
    print(run_caseb().fun_a())
    print(run_caseb().fun_i())
# coding:utf-8
import importlib

class run_caseb:
    bala = "balabalabala"

    def fun_a(self):
        return True

    def fun_i(self,):
        name = "a"
        case_name = "casea"
        # 导入run_case1 模块中run类
        imp_class = getattr(importlib.import_module("deploy.a.run_%s" % case_name), "run_%s" % case_name)
        # 创建对象
        exp = imp_class()
        print(exp.v1)
        print(exp.c1)
        # 导入方法
        imp_fun = getattr(exp, "run_a")(3, 4)
      
        return imp_fun


if __name__ == "__main__":
    print(run_caseb().fun_a())
    print(run_caseb().fun_i())
方法二

 

运行结果

 

posted @ 2022-01-14 17:29  Phoenixy  阅读(903)  评论(0编辑  收藏  举报