Interesting stuff.  Thanks.

On 08/06/2012 07:53 PM, alex23 wrote:
On Aug 4, 6:48 am, Tobiah<t...@tobiah.org>  wrote:
I have a bunch of classes from another library (the html helpers
from web2py).  There are certain methods that I'd like to add to
every one of them.  So I'd like to put those methods in a class,
and pass the parent at the time of instantiation.  Web2py has
a FORM class for instance.  I'd like to go:

         my_element = html_factory(FORM)

Then my_element would be an instance of my class, and also
a child of FORM.

I've lately begun to prefer composition over inheritance for
situations like this:

     class MyElementFormAdapter(object):
         def __init__(self, form):
             self.form = form

         def render_form(self):
             self.form.render()

     my_element = MyElementFormAdapter(FORM)
     my_element.render_form()
     my_element.form.method_on_form()

Advantages include being more simple and obvious than multiple
inheritance, and avoiding namespace clashes:

     class A(object):
         def foo(self):
             print 'a'

     class B(object):
         def foo(self):
             print 'b'

     class InheritFromAB(A, B):
         pass

     class AdaptAB(object):
         def __init__(self, a, b):
             self.a = a
             self.b = b

     >>>  inherit = InheritFromAB()
     >>>  inherit.foo()
     a
     >>>  adapt = AdaptAB(A(), B())
     >>>  adapt.a.foo()
     a
     >>>  adapt.b.foo()
     b

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to