Re: How to subclass a family

Discussion in 'Python' started by Devin Jeanpierre, Apr 9, 2013.

  1. On Mon, Apr 8, 2013 at 5:44 AM, Antoon Pardon
    <> wrote:
    > Now of course I could subclass every class from the original family
    > from Foo1 to Foon but that would mean a lot of duplicated code. Is
    > there a way to reduce the use of duplicated code in such circumstances?


    As a rule, if there's duplicate code you can stuff it in a function.

    def create_subclass(Foo):
    class Far(Foo):
    def boo(self, ...)
    do something different
    if whatever:
    self.bar(...)
    else:
    super(Far, self).boo(self, ...)
    return Far

    Far1 = create_subclass(Foo1)
    Far2 = create_subclass(Foo2)
    ...

    Of course, this doesn't preserve the names of the subclasses properly.
    To do that you can add a parameter, for the name, although this is a
    little repetitive. Alternatively you can subclass yet again, as in:

    class Far1(create_subclass(Foo1)): pass

    Or you can even change the approach to a class decorator that adds a method:

    def add_method(cls):
    def boo(self, ...):
    do something different
    if whatever:
    self.bar(...)
    else:
    super(cls, self).boo(...)

    @add_method
    class Far1(Foo1): pass

    @add_method
    class Far2(Foo2): pass

    As a wise man once said, TIMTOWTDI. :(

    -- Devin
     
    Devin Jeanpierre, Apr 9, 2013
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jstorta
    Replies:
    3
    Views:
    446
    jstorta
    Feb 20, 2006
  2. S.Volkov
    Replies:
    2
    Views:
    221
    S.Volkov
    Mar 12, 2006
  3. Trans
    Replies:
    8
    Views:
    323
    Robert Klemme
    Oct 23, 2008
  4. Antoon Pardon

    How to subclass a family

    Antoon Pardon, Apr 8, 2013, in forum: Python
    Replies:
    1
    Views:
    118
    Steven D'Aprano
    Apr 9, 2013
  5. Arnaud Delobelle

    Re: How to subclass a family

    Arnaud Delobelle, Apr 8, 2013, in forum: Python
    Replies:
    0
    Views:
    301
    Arnaud Delobelle
    Apr 8, 2013
Loading...

Share This Page