使用getattr访问方法 [英] Accessing a method using getattr
问题描述
在创建新的类实例时,我试图在其他类中调用方法,但是无法使其正常工作.这就是我所拥有的:
When creating a new class instance, I'm trying to call a method in a different class however can't get it to work. Here's what I have:
class DataProject(object):
def __init__(self, name=none,input_file=None,datamode=None,comments=None,readnow=True):
..............
# here's where I'm trying to call the method in the other class
if type(input_file) == str:
self.input_file_format = self.input_file.split(".")[-1]
if readnow:
getattr(Analysis(),'read_'+self.input_file_format)(self,input_file)
class Analysis(object):
def __init__(self):
pass # nothing happens here atm
def read_xlsx(self,parent,input_file):
"""Method to parse xlsx files and dump them into a DataFrame"""
xl = pd.ExcelFile(input_file)
for s in sheet_names:
parent.data[s]=xl.parse(s)
当我使用afile.xlxs作为输入运行此命令时,我得到一个NameError: global name 'read_xlsx' is not defined
,这使我认为我刚刚发现了我的Python知识方面的一个巨大漏洞(不是虽然很多,但它们往往很难看,就像大片森林...).
I'm getting a NameError: global name 'read_xlsx' is not defined
when I run this with afile.xlxs as input which made me think that I just discovered a massive hole in my Python knowledge (not that there aren't many but they tend to be hard to see, sort of like big forests...).
我本以为getattr(Analysis(), ... )
将访问全局名称空间,在其中可以找到Analysis类及其方法.实际上print(globals().keys())
表明Analysis是其中的一部分:
I would have thought that getattr(Analysis(), ... )
would access the global name space in which it would find the Analysis class and its methods. And in fact print(globals().keys())
shows that Analysis is part of this:
['plt', 'mlab', '__builtins__', '__file__', 'pylab', 'DataProject', 'matplotlib', '__package__', 'W32', 'Helpers', 'time', 'pd', 'pyplot', 'np', '__name__', 'dt', 'Analysis', '__doc__']
我在这里想念什么?
完整的回溯是:
Traceback (most recent call last):
File "C:\MPython\dataAnalysis\dataAnalysis.py", line 101, in <module>
a=DataProject(input_file='C:\\MPython\\dataAnalysis\\EnergyAnalysis\\afile.xlxs',readnow=True)
File "C:\MPython\dataAnalysis\dataAnalysis.py", line 73, in __init__
getattr(Analysis(),'read_'+self.input_file_format)(self,input_file)
File "C:\MPython\dataAnalysis\dataAnalysis.py", line 90, in read_xls
read_xlsx(input_file)
NameError: global name 'read_xlsx' is not defined
我的主要电话是:
if __name__=="__main__":
a=DataProject(input_file='C:\\MPython\\dataAnalysis\\EnergyAnalysis\\afile.xlx',readnow=True)
推荐答案
从完整的追溯中看来,您的DataProject
类正在(成功地)调用Analysys.read_xls
方法,而该方法又试图调用
From the full traceback, it appears that your DataProject
class is calling (successfully) the Analysys.read_xls
method, which in turn is trying to call read_xlsx
. However, it's calling it as a global function, not as a method.
也许您只需要替换第90行的代码,将read_xlsx(input_file)
转换为self.read_xlsx(input_file)
,尽管您可能还需要为父DataProject
实例传递一个额外的参数.
Probably you just need to replace the code on line 90, turning read_xlsx(input_file)
into self.read_xlsx(input_file)
, though you might need to pass an extra parameter for the parent DataProject
instance too.
这篇关于使用getattr访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!