Reputation: 335
How do I construct a method name to use with an instantiated class? I'm trying to run a method in a class 'jsonmaker' where the method corresponds to the datatype specified in the filein string.
for filein in filein_list:
datatype = filein[(filein.find('_')):-8]
method_name = pjoin(datatype + 'populate')
instantiated_class.method_name(arg1, arg2, arg3)
When I try the above code I get the error message
'AttributeError: 'jsonmaker' object has no attribute 'method_name''
There is in fact a method in jsonmaker that matches pjoin(datatype + 'populate') so how do I tell the class to recognize that? Sorry if I'm not explaining this well.
Upvotes: 1
Views: 44
Reputation: 78564
You can't reference the attribute of a class instance by putting a variable directly behind a dot reference. Not even when the variable references a string which is same as the name of the attribute.
You could instead use getattr
to get the method
from the string and then call it with those parameters:
getattr(instantiated_class, method_name)(arg1, arg2, arg3)
Upvotes: 2