Python如何循环动态调用类方法并获取返回值存入列表
问题根因
exec()函数的作用是执行传入的字符串形式代码片段,本身固定返回None,不会返回代码块内部的运行结果,因此直接追加exec()的执行结果只能拿到全None的列表,和类方法内部的return值没有关联。
另外你当前定义的类方法未加对应装饰器,直接通过类调用虽然能运行,但不符合Python类的写法规范,建议根据使用场景添加@staticmethod装饰器,或者写成标准实例方法。
推荐写法(安全简洁)
用Python内置的getattr()函数动态获取类/实例的方法对象,再执行调用即可拿到返回值,不存在代码注入风险,是动态调用属性/方法的标准方案:
class a: @staticmethod def one(): return "one" @staticmethod def two(): return "two" b = ['one', 'two'] c = [] for method_name in b: # 动态获取类上的方法对象 method = getattr(a, method_name) # 调用方法拿到返回值后追加到列表 c.append(method()) print(c) # 输出结果:['one', 'two']
如果方法需要访问实例属性,写成标准实例方法即可,先创建类实例再通过实例获取方法:
class a: def one(self): return "one" def two(self): return "two" # 先创建类实例 obj = a() b = ['one', 'two'] c = [getattr(obj, method_name)() for method_name in b] print(c) # 输出结果:['one', 'two']
不推荐的exec写法(仅作原理说明)
如果一定要用exec()实现,需要在exec执行的代码内部,把方法返回值赋值给外部可访问的变量,再手动追加到列表。注意这种写法如果方法名来自不可信输入,会存在任意代码执行的安全风险:
class a: @staticmethod def one(): return "one" @staticmethod def two(): return "two" b = ['one', 'two'] c = [] res = None for method_name in b: exec(f"res = a.{method_name}()") c.append(res) print(c) # 输出结果:['one', 'two']
内容的提问来源于stack exchange,提问作者Anonymous
相关产品推荐
相关产品推荐

