Exec inside a class method to call other class methods?
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Thu Dec 25 13:55:51 EST 2008
Matthew Dubins:
> def parse(self, data, data_type)
> exec "self.__parse_%s(data)" % data_type
> For some reason, *it didn't work*.
You can try defining this class attribute:
data_types = set("nocall DOB gender Prematurity email languages phone
cname pname address duedate".split())
And then a possible method can be:
def parse(self, data, data_type):
if data_type in Classname.data_types:
getattr(self, "__parse_" + data_type)(data)
If performance isn't a problem you can move data_types inside the
parse method.
If performance is a problem, data_types may become a dict, whose
values are references to the methods. That you can use as:
def parse(self, data, data_type):
if data_type in data_types:
data_types[data_type](data)
Or even as (but may be a little slower):
def parse(self, data, data_type):
data_types.get(data_type, lambda x: None)(data)
Bye,
bearophile
More information about the Python-list
mailing list