programming container object

Paul McGuire ptmcg at austin.rr.com
Mon Dec 17 09:23:42 EST 2007


On Dec 17, 2:31 am, Paul McGuire <pt... at austin.rr.com> wrote:
> On Dec 17, 1:18 am, "bambam" <da... at asdf.asdf> wrote:
>
>
>
>
>
> > I wish to create a generic container object, devlist, such that
>
> >     devlist.method(arguments)
>
> > runs as
>
> >     for each dev in devlist.pool:
> >         dev.method(arguments)
>
> > and
> >     s = devlist.method(arguments)
>
> > runs as
>
> >     for each dev in devlist.pool:
> >         s.append(dev.method(arguments))
>
> > ...but it is outside my ability to do so.
>
> > Can anyone provide an example of how to do that?
>
> > Thanks,
> > Steve
>
> Ok, I'll take a stab at it.
>
> -- Paul
>
> class DevList(object):
>     def __init__(self, objs):
>         self.devpool = objs
>
>     def __getattribute__(self,attrname):
>         if attrname == "devpool":
>             return object.__getattribute__(self,attrname)
>         def ret(*args):
>             return [ getattr(p,attrname)(*args) for p in
> self.devpool ]
>         return ret
>
> dl = DevList([1,2,3])
> print dl.__str__()
>
> prints:
>
> ['1', '2', '3']- Hide quoted text -
>
> - Show quoted text -

Here's some expanded demo code for the previously-posted DevList
class:

from math import sqrt

class NumberWrapper(object):
    def __init__(self,value=0):
        self.value = value

    def inverse(self):
        if self.value != 0:
            return 1.0/self.value
        else:
            return None

    def sqrt(self):
        return sqrt(self.value)

    def incrBy(self,offset):
        self.value += offset
        return self.value

dl = DevList([NumberWrapper(i) for i in range(5)])
print dl.sqrt()
print dl.inverse()
print dl.incrBy(10)
print dl.sqrt()
print dl.inverse()

prints:

[0.0, 1.0, 1.4142135623730951, 1.7320508075688772, 2.0]
[None, 1.0, 0.5, 0.33333333333333331, 0.25]
[10, 11, 12, 13, 14]
[3.1622776601683795, 3.3166247903553998, 3.4641016151377544,
3.6055512754639891, 3.7416573867739413]
[0.10000000000000001, 0.090909090909090912, 0.083333333333333329,
0.076923076923076927, 0.071428571428571425]

-- Paul



More information about the Python-list mailing list