How can I define __getattr__ to operate on all items of container and pass arguments?

MRAB python at mrabarnett.plus.com
Tue Feb 15 15:59:30 EST 2011


On 15/02/2011 20:29, Jeremy wrote:
> I have a container object.  It is quite frequent that I want to call a function on each item in the container.  I would like to do this whenever I call a function on the container that doesn't exist, i.e., the container would return an attribute error.
>
> For example
>
> class Cont(object):
>      def __init__(self):
>          self.items = []
>
>      def contMethod(self, args):
>          print("I'm in contMethod.")
>
>      def __getattr__(self, name):
>          for I in self.items:
>              # How can I pass arguments to I.__dict__[name]?
>              I.__dict__[name]
>
>
>>>> C = Cont()
>>>> # Add some items to C
>>>> C.contMethod()
> I'm in contMethod.
>>>> C.itemMethod('abc')
> ??????????
>
>
> The trouble I'm getting into is that I can't pass arguments to the attributes in the contained item.  In the example above, I can't pass 'abc' to the 'itemMethod' method of each item in the container.
>
> Does someone know how I can accomplish this?
>
Try calling it. All you're currently doing is looking it up and then
discarding it.



More information about the Python-list mailing list