如何构造与实例化的类一起使用的方法名称?我正在尝试运行'jsonmaker‘类中的一个方法,其中该方法与filein字符串中指定的数据类型相对应。
for filein in filein_list:
datatype = filein[(filein.find('_')):-8]
method_name = pjoin(datatype + 'populate')
instantiated_class.method_name(arg1, arg2, arg3)当我尝试上面的代码时,我得到错误信息
'AttributeError: 'jsonmaker' object has no attribute 'method_name''事实上,jsonmaker中有一个方法可以匹配pjoin(datatype +‘填充’),那么我该如何告诉这个类去识别它呢?如果我解释得不够好,我很抱歉。
发布于 2016-07-22 01:59:14
您不能通过将变量直接放在点引用后面来引用类实例的属性。即使当变量引用与属性名称相同的字符串时也不会。
相反,您可以使用getattr从字符串中获取method,然后使用这些参数调用它:
getattr(instantiated_class, method_name)(arg1, arg2, arg3)https://stackoverflow.com/questions/38511227
复制相似问题