Computed attribute names

paul paul at
Wed Apr 8 21:03:00 CEST 2009

Dale Amon schrieb:
> There are a number of things which I have been used
> to doing in other OO languages which I have not yet
> figured out how to do in Python, the most important
> of which is passing method names as args and inserting
> them into method calls. Here are two cases I have been
> trying to figure out for a current project. 
> The first is passing methods to dispatcher methods. In
> pseudocode, something like this:
> def dispatcher(self,methodname):
>     self.obj1.methodname()
>     self.obj2.methodname()
I'd say you can use:

method = getattr(self.obj1, 'methodname')

It will raise AttributeError if 'methodname' is not found or the 
(optional) third argument to getattr()

> and another case is selecting behavior of an object by
> setting a type string, with pseudo code like this:
>     self.IBM029 = re.compile([^acharset]
>     self.IBM026 = re.compile([^anothercharset]
>     self.type = "IBM029"
>     errs      = self.(self.type).findall(aCardImage)
same here, or use a class/module-level dict like

symbol_table = {
   'IBM029': re.compile([^...]),
   'IBM026': re.compile([^...])

and symbol_table[self.type].findall(something)


> --

More information about the Python-list mailing list