Saturday, 7 September 2013

Accessing a method using 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 dumpt them into a DataFrame"""
xl = pd.ExcelFile(input_file)
for s in sheet_names:
parent.data[s]=xl.parse(s)
I'm getting a NameError: global name 'read_xlsx' is not defined 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...).
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__']
What am I missing here?

No comments:

Post a Comment