Python: edit child methods for objects contained in child object
<p>I apologize for the title...couldn't think of anything else. I have 2 classes as follows:</p>

<pre><code>class Widget:
    def __init__(self):
        ...

    def remove(self):
        widgets_to_remove.add(self)

    def update(self, events, mouse_pos):
        pass

    def draw(self, screen):
        pass


class Widget_bundle(Widget):
    def __init__(self, widget_group):
        Widget.__init__(self)
        self.widget_group = widget_group # list containing objects inheriting from Widget
        self.call_for_all("remove")

    def call_for_all(self, func, *args):
        for w in self.widget_group:
            getattr(w, func)(*args)
</code></pre>

<p>the code works but I would like it if there was a way to call a method defined by a <code>Widget</code> object on a <code>Widget_bundle</code> object and have that method called by all objects in <code>widget_group</code>.  The obvious solution is to make a method for EVERY SINGLE POSSIBLE METHOD and use a for loop to iterate over the objects, or use my <code>call_for_all method</code>, which requires the function as a string and complicates other parts of the code I didn't include.  Is there a third solution?</p>

<p>It sounds like this is your situation:</p>

<p>You have a class <code>Widget_bundle</code> that has a property <code>Widget_bundle.widget_group</code>. That property is a list of classes <code>Widget</code>.</p>

<p>You want to make a call, for example, <code>Widget_bundle.remove()</code> and translate that to a call <code>Widget.remove()</code> for each <code>Widget</code> in <code>Widget_bundle.widget_group</code>.</p>

<p>One way to approach this would be to customise the <code>Widget_bundle.__getattr__</code> method.</p>

<pre><code>class Widget_bundle(Widget):

    def __init__(self, widget_group):
        Widget.__init__(self)
        self.widget_group = widget_group

    def __getattr__(self, attr):
        def _bundle_helper(*args, **kwargs):
            for widget in self.widget_group:
                getattr(widget, attr)(*args, **kwargs)

        return _bundle_helper
</code></pre>

<p>Or using <code>functools</code>:</p>

<pre><code>import functools


class Widget_bundle(Widget):

    def __init__(self, widget_group):
        Widget.__init__(self)
        self.widget_group = widget_group

    def __getattr__(self, attr):
        return functools.partial(self._bundle_helper, attr)

    def _bundle_helper(self, attr, *args, **kwargs):
        for widget in self.widget_group:
            getattr(widget, attr)(*args, **kwargs)
</code></pre>

<p>Now you can call <code>Widget_bundle.remove()</code>.</p>

<p>I referred to <a href="http://stackoverflow.com/questions/3434938/python-allowing-methods-not-specifically-defined-to-be-called-ala-getattr">this StackOverflow question</a>.</p>

python inheritance methods