Computed attribute names

Albert Hopkins marduk at letterboxes.org
Wed Apr 8 14:59:20 EDT 2009


On Wed, 2009-04-08 at 19:47 +0100, Dale Amon wrote:
> 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()

The built-in getattr() function:

def dispatcher(self, methodname):
    getattr(self.obj1, methodname)()
    getattr(self.obj2, methodname)()


> 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:

errs = getattr(self, self.type).findall(aCardImage)






More information about the Python-list mailing list