I have a class with some built-in methods. This is a abstracted example of what the class might look like:
class Foo:
def __init__(self):
self.a = 0
self.b = 0
def addOneToA(self):
self.a += 1
def addOneToB(self):
self.b += 1
For the sake of simplicity, I've reduced the built-in methods to 2 total, but in actuality my class has closer to 20.
Next I have another class that is designed to work on a list of Foo instances.
class Bar:
def __init__(self, fooInstances):
self.fooInstances = fooInstances
# Bar([Foo(), Foo(), Foo()])
What if I wanted to apply one of the Foo methods to the Foo instances in Bar?
class Bar:
# ...
def addOneToA(self):
for fooInstance in self.fooInstances:
fooInstance.addOneToA()
def addOneToB(self):
for fooInstance in self.fooInstances:
fooInstance.addOneToB()
The example above is one way of doing what I described, but it seems like a great deal of repetitive code to do this if there were 20 class methods of Foo. Alternatively, I could do something like this:
class Bar:
# ...
def applyFooMethod(self, func, *args):
for fooInstance in self.fooInstances:
fooInstance.func(args)
But I would prefer to have something that would allow me to call .addOneToA() on Bar and have it be applied to all Foo instances in Bar. Is there a clean way to do this without defining all methods of Foo inside Bar?
Barclass is a filter that works on the list ofFooobjects and basically narrows down the list based on parameters. For example, I could create aBarclass likebar = Bar([Foo(), Foo(), Foo()])then run something likebar.filterElementsWith("a", "<=", 5)and this would eliminate allFooinstances in thefooInstanceslist whereais less than or equal to 5. The actual code is a bit more involved but I'll update the question with this information when I get a chance.